← Back to Tutorials Chapter 7

Exceptions

Try/Catch/Finally

Exceptions handle runtime errors gracefully without crashing the program.

try {
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[5]);  // Throws IndexOutOfRangeException
} catch (IndexOutOfRangeException ex) {
    Console.WriteLine($"Error: {ex.Message}");
} catch (Exception ex) {
    Console.WriteLine($"General error: {ex.Message}");
} finally {
    Console.WriteLine("This runs whether or not an exception occurs");
}

Custom Exceptions

class AgeException : Exception {
    public AgeException(string message) : base(message) { }
}

void ValidateAge(int age) {
    if (age < 0 || age > 150) {
        throw new AgeException("Age must be between 0 and 150");
    }
}

Using Statement (IDisposable)

using (var reader = new StreamReader("file.txt")) {
    string content = reader.ReadToEnd();
}  // Automatically disposes the resource

Exception Properties

try { /* code */ }
catch (Exception ex) {
    Console.WriteLine(ex.Message);      // Human-readable description
    Console.WriteLine(ex.StackTrace);   // Call stack
    Console.WriteLine(ex.InnerException); // Nested exception
}
C# exception handling flow

Practice Task

Write a C# program that applies the concepts covered in this chapter. Experiment with different inputs and test your understanding.