Summary: in this tutorial, you’ll learn about C# UnhandledException
and how to provide a global exception handler.
Introduction to the C# UnhandledException
In C#, an unhandled exception is an exception that occurs but doesn’t have a corresponding exception handler. If the exception remains unhandled, the program will crash.
Typically, when an exception occurs, the .NET runtime will look for an exception handler that can handle the exception. If it cannot find one, the runtime terminates the application and displays an error message.
To prevent this from happening, you can handle the exception in your code using the try...catch
block:
try
{
// Code that might throw an exception
}
catch (Exception ex)
{
// Code that handles the exception
}
Code language: C# (cs)
In this example, the code in the try
block might cause an exception. And the catch
block handles the exception if it occurs.
The catch
block can handle the exception by logging the error, rethrowing the same or new exception, or taking other actions.
To provide a global exception handler, you can subscribe the AppDomain.UnhandledException
event. This event is raised whenever an unhandled exception occurs. For example:
using static System.Console;
int Divide(int a, int b)
{
return a / b;
}
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(HandleException);
// cause an exception
var result = Divide(10, 0);
WriteLine(result);
static void HandleException(object sender, UnhandledExceptionEventArgs e)
{
WriteLine($"Sorry, there was a problem occurs. The program is terminated. \n {e.ExceptionObject}");
}
Code language: C# (cs)
In this example, the Main
method subscribes to AppDomain.UnhandledException
event. If an exception occurs but no handler is available to catch it, the HandleException
method will execute to handle the exception.
By doing this, you can prevent your program from crashing and deliver a better user experience.
Summary
- If an exception occurs but no handler is found, the .NET runtime will look for a global exception handler.
- Subscribe to the
AppDomain.UnhandledException
event to handle unhandled exceptions.