I have a simple try-catch-finally block in C#. As I understand it, the "finally" block is useful because its code will execute even if an exception is thrown inside the catch block (barring some special exception types).
However, in the simple example below, the finally block never executes. Visual Studio says an unhandled exception is occurring in my catch block and then the program terminates. I thought execution would just jump to the finally block instead.
How can I ensure the code in the finally block executes even when an exception occurs in the catch block?
public static void Main(string[] args)
{
try
{
throw new Exception("Apple");
}
catch (Exception ex)
{
throw new Exception("Banana");
}
finally
{
// This line never executes. Why?
Console.WriteLine("Carrot");
}
}
What and why it happens
The result depends on what button you click when the program crashes. If you're slow, the Windows Error Reporting (WER) dialog will show "Debug" and "Close program". If you press the "Close program" button, the program is terminated by the operationg system without any chance of writing something else to console.
If you're fast enough to hit the "Cancel" button, then the Windows Error Reporting part will be cancelled and control goes back to your program. It will then write "Carrot" to the Console.
Therefore, this is not a .NET issue but it's a matter on how Windows reacts to exception dispatching.
How to get control over it
To disable the WER dialog, you can use WerAddExcludedApplication . To get rid of the Debug dialog, you can use SetErrorMode.
Please make yourself familiar with the disadvantages of using those methods. Read Raymond Chen's comments on WerAddExcludedApplication and check whether SetThreadErrorMode might be in favor.
Your code may then look like this: