Labs ICT
โญ Pro Login

Exception Handling

Things go wrong in programs. Files do not exist, users type invalid input, network connections fail. Exception handling is how you deal with these problems without crashing your entire application.

What Is an Exception?

An exception is an error that occurs during program execution. When C# encounters an error it cannot handle, it throws an exception. If you do not catch it, your program crashes.

// This will crash your program
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]);  // IndexOutOfRangeException!

Nobody wants their app to crash in front of a user. That is where try-catch comes in.

try-catch

try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]);
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Error: Index is out of range.");
    Console.WriteLine($"Details: {ex.Message}");
}

The code that might cause an exception goes inside try. If an exception happens, C# jumps to the matching catch block instead of crashing. The ex variable contains information about what went wrong.

Multiple catch Blocks

try
{
    Console.Write("Enter a number: ");
    int number = int.Parse(Console.ReadLine());

    int[] data = { 10, 20, 30 };
    Console.WriteLine(data[number]);
}
catch (FormatException ex)
{
    Console.WriteLine("That was not a valid number.");
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Number is out of range.");
}
catch (Exception ex)
{
    Console.WriteLine($"Something unexpected happened: {ex.Message}");
}

You can have multiple catch blocks to handle different types of exceptions. Put the most specific ones first and the general Exception catch last.

finally

The finally block runs no matter what โ€” whether an exception occurred or not. It is typically used for cleanup:

System.IO.StreamReader? reader = null;

try
{
    reader = new System.IO.StreamReader("data.txt");
    string content = reader.ReadToEnd();
    Console.WriteLine(content);
}
catch (FileNotFoundException)
{
    Console.WriteLine("File not found.");
}
finally
{
    // Always close the file, even if an error occurred
    reader?.Close();
    Console.WriteLine("Cleanup complete.");
}

Throwing Exceptions

You can throw your own exceptions to signal errors in your methods:

void SetAge(int age)
{
    if (age < 0 || age > 150)
    {
        throw new ArgumentOutOfRangeException(nameof(age), "Age must be between 0 and 150.");
    }
    Console.WriteLine($"Age set to {age}");
}

try
{
    SetAge(-5);
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.Message);
}

Throwing exceptions makes your methods self-documenting. Anyone using your code knows exactly what can go wrong and how to handle it.

๐Ÿงช Quick Quiz

What does try-catch do?