try {
// Do stuff
}
catch (Exception e) {
throw;
}
finally {
// Clean up
}
In the above block when is the finally block called? Before the
If there is an unhandled exception inside a catch handler block, the finally block gets called exactly zero times
static void Main(string[] args)
{
try
{
Console.WriteLine("in the try");
int d = 0;
int k = 0 / d;
}
catch (Exception e)
{
Console.WriteLine("in the catch");
throw;
}
finally
{
Console.WriteLine("In the finally");
}
}
Output:
C:\users\administrator\documents\TestExceptionNesting\bin\Release>TestExceptionNesting.exe
in the try
in the catch
Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at TestExceptionNesting.Program.Main(String[] args) in C:\users\administrator\documents\TestExceptionNesting\TestExceptionNesting.cs:line 22
C:\users\administrator\documents\TestExceptionNesting\bin\release>
I got asked this question today at an interview and the interviewer kept going back "are you sure the finally doesn't get called?" I was uncertain if it was meant a trick question or the interviewer had something else in mind and wrote the wrong code for me to debug so I came home and tried it (build and run, no debugger interaction), just to put my mind at rest.