And Finally...

  • Thread starter Thread starter Andy Turner
  • Start date Start date
A

Andy Turner

I was just pondering about what the Finally in an exception actually
does. Well, I realise that it always gets called regardless of whether
the exception is thrown or not, but isn't that the same as the next
lines of code? What's the difference between these two bits of code:

try
{
WriteFile();
}
catch
{
// Oh dear
Trace.Write ("Data lost");
}
finally
{
// cleanup code
CloseFile();
}



and



try
{
WriteFile();
}
catch
{
// Oh dear
Trace.Write ("Data lost");
}

// Cleanup code
CloseFile();



Cheers



andyt
 
Andy,

Easy. In the second section of code, if the WriteFile method throws an
exception, then the CloseFile method never gets called, as the method is
exited. The finally clause will guarantee that the code gets executed,
which seems important in this case, since you need to clean up resources
initialized in the method.

Hope this helps.
 
If Trace.Write happens to throw another exception - then CloseFile wil never
gets executed in the second scenario.
 
Hi, Andy

main issue with second variant is very clear if you put return; into catch
clause. For such case only finally block guarantees that file will be closed
before control will be passed out of current routine.

HTH
Alex
 
There's not a tremendous amount of difference in your example (except for
differences already mentioned, like if something in the catch block throws).

Use of the finally becomes a lot more obvious if you have a method that is
only looking for a specific type of exception, like this:

try
{
WriteFile();
}
catch (SomeApplicationExceptionTypeThatICanHandle e)
{
// Oh dear
Trace.Write("Data Lost. Message: " + e.message);
}
finally
{
CloseFile();
}


Note that if some exception other than the one that I am looking for occurs,
the catch never gets executed, but the close file will still be called. Or,
maybe you have a method that doesn't care so much about the exception (the
error handling code occurs "higher up" in the stack:

try
{
WriteFile();
}
finally
{
CloseFile();
}


The finally lets you make a distinction between what is supposed to happen
when the method exits, regardless of the exception, and the actual error
handling code. The error handling (catch) code can even be relocated to a
different method in the call chain.
 
Yep. And things get even clearer if the method doesn't handle the exception
itself, i.e. doesn't catch it or rethrows it.
This:

try
{
WriteFile();
}
finally
{
// cleanup code
CloseFile();
}

is much cleaner than:

try
{
WriteFile();
}
catch
{
// Oh dear
CloseFile();
throw;
}
// cleanup code
CloseFile();

Especially if more than one line of cleanup is needed.

Note that the using clause has a similar effect; It calls Dispose in a
finally block.

Niki
 
if your thread is aborting, paritcularly important is asp.net - you'll for
sure want the finally clause.
 
Back
Top