Exception Handling
Exceptions are runtime disruptions caused by errors. C# uses try-catch-finally blocks to handle errors gracefully, preventing application crashes.
1 Try-Catch-Finally Flow Control
Exception handling flows systematically:
- try: Wraps code blocks that may throw exceptions.
- catch: Intercepts and handles errors if they occur.
- finally: Executes cleanup code after try/catch, regardless of whether an error was thrown.
2 Exception Code
Let's run a program handling a division-by-zero error using try-catch blocks:
C# — Exceptions
▶ Run Code
using System;
class Program {
static void Main() {
try {
int x = 10;
int y = 0;
int result = x / y; // Throws DivideByZeroException
} catch (DivideByZeroException e) {
Console.WriteLine("Exception Caught: Division by zero is invalid.");
} finally {
Console.WriteLine("Finally block executed. Resources released.");
}
Console.WriteLine("Program continues execution smoothly...");
}
}
3 Code Challenge
Challenge: Write a method called `CheckAge(int age)` that throws an `ArgumentOutOfRangeException` if age is negative. Test it inside a try-catch block in `Main()` and print the caught error message.