I see that the Finally
in Try .. Catch
will always execute after any parts of the execution of the try catch block.
Is it any different to
The difference is when the code in the try
block throws an exception that isn't caught by the catch
block.
Normally a catch
block would catch a specific type of exception, and let anything else through. In that case, the finally
block will still run.
The finally
block will also run if the code in the try
block return
s.
Doing clean up in a finally block is to ensure that it is run. If the catch block doesn't deal with the exception (ie. it just logs it), or even causes another exception, the code in the finally block will still run.
Code with four radio buttons:
Finish CATCH
private void checkFinally()
{
try
{
doFinally();
}
catch
{
Console.WriteLine(" Breaking news: a crash occured. ");
}
}
private void doFinally()
{
Console.WriteLine(" ");
Console.Write("Here goes: "
+ (radioReturnInTry.Checked ? "2. Return in try: "
: (radioReturnInCatch.Checked? "3. Retrun in catch: "
: (radioThrowInCatch.Checked? "4. Throw in catch: "
: "1. Continue in catch: "))) );
try
{
if (radioReturnInTry.Checked)
{
Console.Write(" Returning in try. ");
return;
}
Console.Write(" Throwing up in try. ");
throw new Exception("check your checkbox.");
}
catch (Exception ex)
{
Console.Write(" ...caughtcha! ");
if (radioReturnInCatch.Checked)
{
Console.Write("Returning in catch. ");
return;
}
if (radioThrowInCatch.Checked)
{
Console.Write(" Throwing up in catch. ");
throw new Exception("after caught");
}
}
finally { Console.Write(" Finally!!"); }
Console.WriteLine(" Done!!!"); // before adding checkboxThrowInCatch,
// this would never happen (and was marked grey by ReSharper)
}
Output:
To summarize: Finally takes care of two things:
Finally to summarize "FINALLY": Finally does nothing special if you tried,and
And last but not least (finally): If you have an exception in your code that YOU DID NOT CATCH, your code will fly, WITHOUT REACHING THE FINALLY.
Hope this is clear. (Now it is to me...)
Moshe
This is a good idea when dealing with database connections or anytime objects need to be disposed of. Just in case something goes wrong while running queries, you can still close the connection safely. It also helps to clean up code that the block outside the try/catch/finally block is not able to access.
Finally should be used to everything that needs to be done in order to keep a system consistent. This usually means release resources
Finally is always executed, no matter what exception was thrown. It should be used to release resources, in the following cases:
Let me give a complete example. Imagine that that you are sending messages through the network. In pseudo-code:
// With finally | //Without finally
try{ | try{
send_message() | send_message()
} catch(NetworkError){ | } catch(NetworkError){
deal_with_exception() | deal_with_exception()
} finally { | }
finalizes_connection() | finalizes_connection()
} |
The only difference of both codes is when what is hold in the try
block raises an exception that is not NetworkError
, for example, MethodNotFound
. In the first case, the method finalizes_connection()
will be called, and in the second one, it will not.
A connection is naturally done through more than one program. So what happens in the case of a MethodNotFound
exception to the other program? In the first case, your program will finish the connection and the other program and it will be happy. In the second case, the other program can be waiting for your response forever. What if the other program can only receive one connection per time? You just bugged the other program as well.
This would also apply for a file, for example, that you opened and other programs wouldn't be able to open for reading (in Windows). And for memory, it is never released and now you have a memory leak.
The Finally block will execute regardless of if the function exits because of an exception. (there are some exceptions to this rule, see this stackoverflow question for more info).
For example:
Try
'Do something
Catch ex As Exception
if 'Some Condition
throw ex
else
'Handle exception
Finally
'Do cleanup
End Try
In this case the Finally block will still be executed even though you may throw an exception out of the function.
This is a good practice to get into because it ensures that your cleanup code always executes. Of course using the Resoource Acquisition Is Initialization idiom is a much cleaner way of ensuring that resources get cleaned up, but I'm not versed enough in VB.net to know if this is possible to do.