It’s easy enough to handle the exception using try/catch blocks. Some application takes benefit of the global exception handler. For Example, if you want to control standard exceptions, you can use your custom global exception handler to handle exceptions such as divided by zero, ArrayOutOfBoundException etc. These exceptions may occur when an unhandled exception is found.

What is Global Exception Handler?

If you want to find every exception in your application, you need to know about the global exception handler. The global exception handler is a type of function. This function is designed to predict the behavior of an application when a system is encountered with a specific exception error.

By using a global error handler event, you may find every exception to identify and remove hidden problems in your application. A global exception handler is mostly used during the development process to help detect possible problems in our program.
Setup the global error handler at the start of the application in Globel.asaxfor ASP.NET application, Program.cs for a console application, or Startup.cs for an MVC application.

In this article, we will use a console application to create a global error handler. If you have a single threaded application, then you can use try/catch block in the main method. This will not catch exceptions outside of the main function or in any other threads.

using System;

class Program {

    static void Main(string[] args) {
        System.AppDomain.CurrentDomain.UnhandledException+=UnhandledExceptionTrapper;
        throw new Exception("Global Exception Handler");
    }

    static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs e) {
        Console.WriteLine(e.ExceptionObject.ToString());
        Console.WriteLine("Press Enter to Exit");
        Console.ReadLine();
        Environment.Exit(0);
    }
}

Keep in mind that you cannot catch load file or type exception generated by the jitter. These exceptions happened before the running of the main method.

Related Articles

Last modified: May 24, 2019

Comments

Write a Reply or Comment

Your email address will not be published.