C# exception handling

Exception handling in C# provides a way to handle runtime errors and unexpected events that occur during program execution. When an exception occurs, it disrupts the normal flow of program execution and can cause the program to terminate prematurely. Exception handling allows you to gracefully handle these errors and continue program execution.

In C#, exceptions are represented by objects of type Exception or one of its derived classes. When an exception occurs, an object of the appropriate exception type is created and thrown using the throw keyword.

Here is an example of exception handling in C#:

refer to:‮tfigi‬idea.com
using System;

class Program
{
    static void Main()
    {
        try
        {
            // Code that may throw an exception
            int a = 10;
            int b = 0;
            int c = a / b;
        }
        catch (DivideByZeroException ex)
        {
            // Handle the exception
            Console.WriteLine("Cannot divide by zero: " + ex.Message);
        }
        finally
        {
            // Code that is always executed, whether an exception occurs or not
            Console.WriteLine("Program complete.");
        }
    }
}

In this example, the try block contains code that may throw an exception (in this case, dividing by zero). If an exception is thrown, it is caught by the catch block, which handles the exception by displaying an error message. The finally block is always executed, regardless of whether an exception occurs or not.

C# also provides the throw statement for manually throwing exceptions. You can create your own exception classes by deriving from the Exception class or one of its derived classes.

Exception handling is an important part of writing robust and reliable code in C#. By handling exceptions gracefully, you can ensure that your program continues to function correctly even when unexpected errors occur.