Monday, February 16, 2009

Try-finally block without catch

We use try-finally block without catch when we want our application to guarantee execution of cleanup code (in finally block) when execution of a block of code. If an exception occurs then the code in finally block will be executed before the exception is thrown to outside.

Consider below example:
void MyMethod1()
{
try
{
MyMethod2();
MyMethod3();
}
catch(Exception e)
{
//do something with the exception
}
}

void MyMethod2()
{
try
{
//perform actions that need cleaning up
}
finally
{
//clean up
}
}

void MyMethod3()
{
//do something
}
If either MyMethod2 or MyMethod3 throws an exception, it will be caught by MyMethod1. However, the code in MyMethod2 needs to run clean up code, e.g. closing a database connection, before the exception is passed to MyMethod1.

No comments: