How to Catch the Unhandled Exceptions in C# ?

Are you looking for a way to catch the unhandled exception and perform the operation like logging etc. before the application terminates ?.

Below is a sample code snippet that demonstrates how to do it in Console Application.

How to Catch the Unhandled Exceptions in C# ?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace AbundantcodeConsole
{ 
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            throw new Exception();
            
        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Console.WriteLine("Unhandled Exception");
            Console.ReadLine();
        }  
    }  
}
1