tags:

views:

87

answers:

4

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

try
{
  return abc;
}
catch(Exception ex)
{
console.Writeline("Exception occur" + ex);
}
A: 
try 
   { 
        return abc; 
   } 
catch(Exception ex) 
   { 
        console.Writeline("Exception occur" + ex); 
        return some_value;
   }
Pramodh
Returning an error code from a `catch` block somewhat defeats the purpose of exceptions.
casablanca
+1  A: 

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.

rerun
@Rerun sorry if my statement is confusing you actually i want to return some values in try cage.
QAZI
you can just use return. Its valid anywhere.
rerun
+1  A: 

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;
    }
}
Lee Sy En
+4  A: 

You can return from anywhere.

fastcodejava
+1 , for good answer
saurabh
3 votes for this, wow!
fastcodejava