JPReddy
JPReddy

Reputation: 65503

Returning from function through catch block, what happens to finally block?

I've try catch finally block and if some exception occurs I'll return from the catch block, so finally block is still executed, if so, when? Before return or after return?

Is this the right practice?

try
{
// do something
}

catch (Exception)
{    
  return false;
}
finally
{
  if (connection.State == ConnectionState.Open) connection.Close();
}

Upvotes: 6

Views: 2710

Answers (4)

supercat
supercat

Reputation: 81159

A finally block will always execute before the code exits a try-catch-finally block (any condition like a ThreadAbortException which prevents the finally block from executing will prevent code from exiting the try-catch-finally block).

Upvotes: 0

TalentTuner
TalentTuner

Reputation: 17556

You can try with your self

private bool test()
    {
        try
        {
            int i = 0;
           int u = 10 / i;
        }

        catch (Exception)
        {
            return false;
        }
        finally
        {

        }
        return true;
    }

so it is a divideby zero exception. When you execute this code , finally will execute and after return will execute.

it is something like Runtime the returned result in case of finally block!

Upvotes: 1

Hoàng Long
Hoàng Long

Reputation: 10848

It will execute "finally" block after return. "Finally" is used for some practice such as close database connection (always need to be done)

Upvotes: 6

Nicolas
Nicolas

Reputation: 6494

finally block is always executed. In your case it is executed before your return statement.

Upvotes: 2

Related Questions