C# ยท Chapter 41 of 46

C# Exceptions (Try/Catch)

Exceptions represent runtime errors, like dividing by zero or accessing an invalid array index. C# uses try/catch blocks to handle exceptions gracefully instead of letting the program crash.

Code that might fail is placed in a try block, and code that handles the failure goes in a catch block. A finally block can run cleanup code regardless of whether an exception occurred.

Syntax
try {
  // risky code
} catch (ExceptionType ex) {
  // handle error
} finally {
  // always runs
}

try, catch, finally

Code that might throw an exception goes inside try. catch blocks handle specific exception types, and finally runs cleanup code (like closing a file) whether or not an exception happened.

Throwing exceptions

You can create and raise your own exceptions using the `throw` keyword, like `throw new ArgumentException("Invalid input");`, useful for enforcing rules in your own methods.

Example 1 (csharp)
using System;

class Program {
  static void Main() {
    try {
      int x = 10 / int.Parse("0");
    } catch (DivideByZeroException ex) {
      Console.WriteLine("Error: " + ex.Message);
    }
  }
}
Output
Error: Attempted to divide by zero.

Dividing by zero throws a DivideByZeroException, which is caught and handled gracefully.

Example 2 (csharp)
using System;

class Program {
  static void Main() {
    try {
      int[] numbers = { 1, 2, 3 };
      Console.WriteLine(numbers[5]);
    } catch (IndexOutOfRangeException) {
      Console.WriteLine("Index was out of range!");
    } finally {
      Console.WriteLine("Done.");
    }
  }
}
Output
Index was out of range!
Done.

The catch block handles the invalid index access, and finally always runs afterward.

Key points

  • try contains code that might throw an exception.
  • catch handles a specific exception type when it occurs.
  • finally runs cleanup code whether or not an exception happened.
  • throw is used to raise your own exceptions manually.
๐Ÿ’ก Note: Catch specific exception types rather than a generic Exception whenever possible, so you handle errors appropriately.

๐Ÿ“ Quick Quiz

1. Which block contains code that might throw an exception?

2. When does the finally block run?

3. Which keyword manually raises an exception?