Is it possible to use return statement in try block?.How,What is the use of the statement.
A:
Sure, you can do it like:
public string X(..)
{
try
{
//do something
return value;
}
catch(Exception ex)
{
throw;
//or return here
}
}
Brian
2010-05-13 16:14:29
It's important that you either throw or return in the catch block. If the try code throws an exception, the return in the try block will not be executed.
Daniel Straight
2010-05-13 16:17:49
**NEVER write `throw ex`!**
SLaks
2010-05-13 16:22:54
+4
A:
Sure, you can use return in a try block, and the syntax is just like everywhere else.
try
{
return 0;
}
catch (Exception e)
{
// handle exception
}
dcp
2010-05-13 16:14:41
A:
Yes.
I can use local variables without having to widen their scope, for example.
int Foo(string bar) {
try {
int biz = int.Parse(bar);
return biz;
} catch(...) {
// Handle bad `bar`
}
}
strager
2010-05-13 16:16:21
+7
A:
You can return from within a try block, but keep in mind that the code in the finally clause will be executed before returning from the method. For example, calling MessageBox.Show(test().ToString());
using the method below will cause two message boxes to appear (the first displaying "3" and the second displaying "1").
int test() { try { return 1; throw new Exception(); } catch (Exception e) { return 2; } finally { MessageBox.Show("3"); } }
TreDubZedd
2010-05-13 16:24:21
Note also that attempting to return from the finally clause results in a compiler error.
TreDubZedd
2010-05-13 17:06:51
+1 to both the answer and the comment for learning me something about the finally block today.
Chuck Wilbur
2010-05-13 21:45:36
A:
An answer for this question is Yes. As an example for this you can refer to the following question: http://stackoverflow.com/questions/2824746/finally-and-return Hope you also get a clarification.
abson
2010-05-13 16:30:36