-3

Is it possible to use return statement in try block?.How,What is the use of the statement.

Ayyappan Anbalagan
  • 11,022
  • 17
  • 64
  • 94

5 Answers5

8

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
  • 2,571
  • 1
  • 15
  • 20
4

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
  • 54,410
  • 22
  • 144
  • 164
0

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
  • 88,763
  • 26
  • 134
  • 176
0

An answer for this question is Yes. As an example for this you can refer to the following question: finally and return Hope you also get a clarification.

Community
  • 1
  • 1
abson
  • 9,148
  • 17
  • 50
  • 69
-1

Sure, you can do it like:

public string X(..)
{
    try
    {
        //do something
        return value;
    }
    catch(Exception ex)
    {
       throw;
       //or return here
    }
}
Brian Mains
  • 50,520
  • 35
  • 148
  • 257
  • 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. – Instance Hunter May 13 '10 at 16:17