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.
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.
using System;
class Program {
static void Main() {
try {
int x = 10 / int.Parse("0");
} catch (DivideByZeroException ex) {
Console.WriteLine("Error: " + ex.Message);
}
}
}Error: Attempted to divide by zero.Dividing by zero throws a DivideByZeroException, which is caught and handled gracefully.
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.");
}
}
}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.
