Hi.
I was wondering if anybody could explain to me the purpose of the Finally block in exception handling. For example, what is the difference between these two pieces of code.
Example 1:
try
{
// open a file
}
catch (IOException ioe)
{
// log the error or something
}
finally
{
// do more stuff
}
Example 2:
try
{
// open a file
}
catch (IOException ioe)
{
// log the error or something
}
// do more stuff
Thanks,
Dave
Loading
arvind haritusPosted Jul 27, 2006, 6:14 AM
your code will be fine if try bolck execute only (means no exception there), if you have any exception then catch block is execute and after that execution is stop. In this situation your connection not close.
so we use finally because of it execute in both condition (try, catch).
DavidPosted Jul 21, 2006, 3:02 PM
Sample 3
try
{
Connection.Open();
// Do something
}
catch(Exception exp)
{
}
Connection.Close();
What would be the difference between that and your sample two?
Dave
Mahesh ChandPosted Jul 21, 2006, 2:16 PM
Finally is very useful when you must execute some code, no matter what happens. You don't need to use it unless you want to make sure some piece of code must be executed. For example, if you are using Connection, and you want to make sure by the end of the method, connection must be close, you put Connection.Close() method in finally.
For example, check these two psuedo code samples:
Sample 1:
try
{
Connection.Open();
// Do something
Connection.Close();
}
catch(Exception exp)
{
}
Sample 2:
try
{
Connection.Open();
// Do something
}
catch(Exception exp)
{
}
Finally
{
Connection.Close();
}
Now let's say there is an exception in code //Do Something, in first sample, connection will not be closed but in second sample, connection will close because Finally block executes at very last.