views:

212

answers:

5

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
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
**NEVER write `throw ex`!**
SLaks
+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
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
+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
Note also that attempting to return from the finally clause results in a compiler error.
TreDubZedd
+1 to both the answer and the comment for learning me something about the finally block today.
Chuck Wilbur
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