C sharp - Exception Handling in C#.

1. What is Exception Handling?

  • Exceptions are errors that occur at runtime (for example: dividing by zero, accessing an invalid index, or working with a null object).

  • Instead of crashing the program, C# provides a way to catch and handle these errors gracefully.


2. The Keywords

try

  • Code that may cause an exception goes inside a try block.

try
{
    int x = 10;
    int y = 0;
    int result = x / y;  // This will throw a DivideByZeroException
}

catch

  • If an exception occurs in the try block, execution jumps to the catch block.

  • You can catch specific exceptions or use a general Exception.

try
{
    int[] numbers = {1, 2, 3};
    Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Error: Tried to access an invalid index.");
    Console.WriteLine($"Details: {ex.Message}");
}
catch (Exception ex) // general catch
{
    Console.WriteLine($"An error occurred: {ex.Message}");
}

finally

  • A finally block runs no matter what, whether an exception happens or not.

  • Often used for cleanup (like closing files, releasing resources).

try
{
    Console.WriteLine("Opening file...");
    // Code that may fail
}
catch (Exception ex)
{
    Console.WriteLine($"Error: {ex.Message}");
}
finally
{
    Console.WriteLine("Closing file..."); // Always runs
}

throw

  • Used to manually raise an exception.

  • You can throw built-in exceptions or create custom ones.

void CheckAge(int age)
{
    if (age < 18)
    {
        throw new ArgumentException("Age must be at least 18.");
    }
    Console.WriteLine("Access granted!");
}

try
{
    CheckAge(15);
}
catch (ArgumentException ex)
{
    Console.WriteLine($"Validation failed: {ex.Message}");
}

3. Flow of Execution

  1. try block executes.

  2. If an exception occurs:

    • Control jumps to the matching catch.

    • If no catch matches, the program crashes.

  3. finally executes always (whether or not there was an exception).


4. Best Practices

  • Catch specific exceptions first, then use a general catch (Exception) as a fallback.

  • Use finally for cleanup (files, database connections, etc.).

  • Don’t overuse exceptions for normal logic flow.