Exception Handling
Prerequisites: Enums
Unlike Java, C# has no checked exceptions — every exception is effectively "unchecked," and the compiler never forces a method to declare or catch one.
try {
int result = 10 / int.Parse("0");
} catch (DivideByZeroException e) {
Console.WriteLine($"Can't divide by zero: {e.Message}");
} finally {
Console.WriteLine("This always runs");
}
using (a statement, distinct from the using import directive)
is C#'s RAII-flavored resource cleanup, guaranteeing Dispose() is
called even if an exception is thrown:
using (var reader = new StreamReader("data.txt")) {
Console.WriteLine(reader.ReadToEnd());
} // reader.Dispose() called automatically here
Common mistakes
- Catching
Exceptionbroadly "to be safe" — exactly the same anti-pattern flagged in Java: catch the specific type you actually expect and know how to handle.
Practice
Write code that attempts int.Parse("abc"), catching
FormatException and printing a friendly message.
Show solution
try {
int n = int.Parse("abc");
} catch (FormatException) {
Console.WriteLine("That wasn't a valid number");
}