1

how we can return some value in try-catch for example

try { return abc; } catch(Exception ex) { console.Writeline("Exception occur" + ex); } 
3
  • 2
    What exactly is your question? Commented Oct 18, 2010 at 5:44
  • Not sure what your asking here are you getting a not all code paths return a value error Commented Oct 18, 2010 at 5:44
  • 2
    Umm, by using return?! Provide more details. Commented Oct 18, 2010 at 5:45

4 Answers 4

3

You can return from anywhere.

Sign up to request clarification or add additional context in comments.

Comments

1

This code will return 2 (exception occured) if you call the method.

int testException() { try { int a = 0; int b = 0; return a / b; //return 1; } catch (System.Exception ex) { return 2; } } 

Comments

1

Try Catch is a way of handling errors in your code that cause you to need to leave the normal flow of the program. Many .net system components throw errors to indicate a condition that is not expected any code can be put in a catch block;

object x; try { x = Func(); } catch(Exception e) { //Set some default Value x = new Object(); //Send an email error SendErrorMail(); } return x; 

If you just need to return inside of a catch you can use a return statement just like you would anywhere else in your code.

2 Comments

sorry if my statement is confusing you actually i want to return some values in try cage.
you can just use return. Its valid anywhere.
0
try { return abc; } catch(Exception ex) { console.Writeline("Exception occur" + ex); return some_value; } 

1 Comment

Returning an error code from a catch block somewhat defeats the purpose of exceptions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.