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 pract开发者_如何转开发ice?
try
{
// do something
}
catch (Exception)
{
return false;
}
finally
{
if (connection.State == ConnectionState.Open) connection.Close();
}
It will execute "finally" block after return. "Finally" is used for some practice such as close database connection (always need to be done)
finally block is always executed. In your case it is executed before your return statement.
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!
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).
精彩评论