It was my assumption that the finally block always gets executed as long as the program is running. However, in this console app, the finally block does not seem to get executed.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
}
}
Output
Note: When the exception was thrown, windows askmed me if I wanted to end the appliation, I said 'Yes.'
It executed actually. Just you didn't notice. Just when you see Windows is checking for a solution to the problem
click Cancel and see it.
When you get the "ConsoleApplication1" has stopped responding, you have two choices.
If you press cancel, the unhandled exception is allowed to continue until eventually the application is terminated. This allows the finally
block to execute. If you do not press cancel then Windows Error Reporting halts the process, collects a minidump and then terminates the application. This means the finally
block is not executed.
Alternatively, if you handle the exception in a higher method you will definitely see the finally
block. For example:
static void unhandled()
{
try
{
throw new Exception();
}
finally
{
Console.WriteLine("finally");
}
}
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;
try
{
unhandled();
}
catch ( Exception )
{
// squash it
}
}
Always gives the output "finally"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With