1. What is Exception Handling?
-
Exceptions are errors that occur at runtime (for example: dividing by zero, accessing an invalid index, or working with a null object).
-
Instead of crashing the program, C# provides a way to catch and handle these errors gracefully.
2. The Keywords
try
try
{
int x = 10;
int y = 0;
int result = x / y; // This will throw a DivideByZeroException
}
catch
-
If an exception occurs in the try block, execution jumps to the catch block.
-
You can catch specific exceptions or use a general Exception.
try
{
int[] numbers = {1, 2, 3};
Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: Tried to access an invalid index.");
Console.WriteLine($"Details: {ex.Message}");
}
catch (Exception ex) // general catch
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
-
A finally block runs no matter what, whether an exception happens or not.
-
Often used for cleanup (like closing files, releasing resources).
try
{
Console.WriteLine("Opening file...");
// Code that may fail
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
finally
{
Console.WriteLine("Closing file..."); // Always runs
}
throw
void CheckAge(int age)
{
if (age < 18)
{
throw new ArgumentException("Age must be at least 18.");
}
Console.WriteLine("Access granted!");
}
try
{
CheckAge(15);
}
catch (ArgumentException ex)
{
Console.WriteLine($"Validation failed: {ex.Message}");
}
3. Flow of Execution
-
try block executes.
-
If an exception occurs:
-
finally executes always (whether or not there was an exception).
4. Best Practices
-
Catch specific exceptions first, then use a general catch (Exception) as a fallback.
-
Use finally for cleanup (files, database connections, etc.).
-
Don’t overuse exceptions for normal logic flow.