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();
}
When catch and finally block both return value, method will ultimately return value returned by finally block irrespective of value returned by catch block.
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs.
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.
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.
It will execute "finally" block after return. "Finally" is used for some practice such as close database connection (always need to be done)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With