When is finally run if you throw an exception from the catch block?
Solution 1:
It would be called after e is re-thrown (i.e. after the catch block is executed)
editing this 7 years later - one important note is that if e
is not caught by a try/catch block further up the call stack or handled by a global exception handler, then the finally
block may never execute at all.
Solution 2:
Why not try it:
This is the output from executing the code below:
outer try
inner try
inner catch
inner finally
outer catch
outer finally
with code (formatted for vertical space):
static void Main() {
try {
Console.WriteLine("outer try");
DoIt();
} catch {
Console.WriteLine("outer catch");
// swallow
} finally {
Console.WriteLine("outer finally");
}
}
static void DoIt() {
try {
Console.WriteLine("inner try");
int i = 0;
Console.WriteLine(12 / i); // oops
} catch (Exception e) {
Console.WriteLine("inner catch");
throw e; // or "throw", or "throw anything"
} finally {
Console.WriteLine("inner finally");
}
}
Solution 3:
After reading all of the answers here it looks like the final answer is it depends:
If you re-throw an exception within the catch block, and that exception is caught inside of another catch block, everything executes according to the documentation.
However, if the re-trown exception is unhandled, the finally never executes.
I tested this code sample in VS2010 w/ C# 4.0
static void Main()
{
Console.WriteLine("Example 1: re-throw inside of another try block:");
try
{
Console.WriteLine("--outer try");
try
{
Console.WriteLine("----inner try");
throw new Exception();
}
catch
{
Console.WriteLine("----inner catch");
throw;
}
finally
{
Console.WriteLine("----inner finally");
}
}
catch
{
Console.WriteLine("--outer catch");
// swallow
}
finally
{
Console.WriteLine("--outer finally");
}
Console.WriteLine("Huzzah!");
Console.WriteLine();
Console.WriteLine("Example 2: re-throw outside of another try block:");
try
{
Console.WriteLine("--try");
throw new Exception();
}
catch
{
Console.WriteLine("--catch");
throw;
}
finally
{
Console.WriteLine("--finally");
}
Console.ReadLine();
}
Here is the output:
Example 1: re-throw inside of another try block:
--outer try
----inner try
----inner catch
----inner finally
--outer catch
--outer finally
Huzzah!Example 2: re-throw outside of another try block:
--try
--catchUnhandled Exception: System.Exception: Exception of type 'System.Exception' was thrown.
at ConsoleApplication1.Program.Main() in C:\local source\ConsoleApplication1\Program.cs:line 53