I have this console application (.NET Framework 4.5.2):
class Program
{
static void Main(string[] args)
{
using (var result = new Result())
{
result.Test();
}
}
}
public class Result : IDisposable
{
public void Test()
{
int a = 1;
int b = 1 / (a - 1);
}
public void Dispose()
{
Console.WriteLine("Dispose");
}
}
Why Dispose
method is not called? A breakpoint is not hit in Dispose
after the DivideByZero
-exception and there is no output on the console (because the app exits).
As per MS Docs: try-finally (C# Reference)
As you are not catching the
DivideByZero
exception and let it be unhandled, on your machine and setup it must be bringing down the application before any other line of code is run and therefore not running thefinally
block.As @Evk has pointed out in below comment, if I run it without attaching debugger, it unwinds the exceptions correctly and executes the finally block. Learn something new everyday.
As per Eric Lippert's answer to Finally Block Not Running?