Reputation: 15
how we can return some value in try-catch
for example
try
{
return abc;
}
catch(Exception ex)
{
console.Writeline("Exception occur" + ex);
}
Upvotes: 1
Views: 262
Reputation: 14692
try
{
return abc;
}
catch(Exception ex)
{
console.Writeline("Exception occur" + ex);
return some_value;
}
Upvotes: 0
Reputation: 5480
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;
}
}
Upvotes: 1
Reputation: 25505
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.
Upvotes: 1