Light Mode Image

C# Unhandled Exception

An unhandled exception occurs when an exception is thrown during the execution of a program, but there is no code to catch and handle that exception.

 

When an exception is not caught, it propagates up the call stack until it reaches the top-level entry point of the application, and if it still remains unhandled, the program terminates, and an error message is displayed.

 

To handle unhandled exceptions, you can use the AppDomain.UnhandledException event or the Application.ThreadException event in a Windows Forms application.

 

Here's an example using the AppDomain.UnhandledException event.

using System;

class Program
{
    static void Main()
    {
        // Subscribe to the UnhandledException event
        AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

        // Your application code
        Console.WriteLine("Enter a number:");
        string userInput = Console.ReadLine();

        try
        {
            int number = Convert.ToInt32(userInput);
            Console.WriteLine("You entered: " + number);
        }
        catch (Exception ex)
        {
            // This catch block will handle exceptions related to the conversion
            Console.WriteLine("Error: " + ex.Message);
        }

        // Rest of your application code
    }

    // Event handler for unhandled exceptions
    static void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
    {
        Exception ex = (Exception)e.ExceptionObject;
        Console.WriteLine("Unhandled Exception: " + ex.Message);
        // You can log the exception or perform any necessary cleanup here
    }
}

 

In this example, the UnhandledExceptionHandler method will be called when an unhandled exception occurs. It's important to note that catching and logging exceptions is crucial for debugging and maintaining robust applications.

 

In a production environment, you might want to log the exception details to a file or another appropriate location for later analysis.