Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 530
JPReddy Avatar asked Dec 08 '10 10:12

JPReddy


People also ask

What will happen when catch and finally block return value?

When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.

Will finally block executed if the catch block executed?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.

Can you return from a catch block?

Yes, we can write a return statement of the method in catch and finally block. There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.

Is finally executed if return in try Python?

Output of the function example_3 is easy to guess. When the return statement in final-block is executed, the function exits so the return statement in try-block is never executed.


1 Answers

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

like image 147
Hoàng Long Avatar answered Sep 29 '22 09:09

Hoàng Long