What is Exception Handling?
Exception handling is like a safety net for your code. It's a way to deal with unexpected errors that might happen when your program is running.
Real-life Analogy
Think of exception handling like wearing a helmet while biking. You hope you won't fall, but if you do, the helmet protects you from serious injury.
Why We Need It:
- Prevents program crashes
- Provides helpful error messages
- Allows graceful recovery from errors
- Helps with debugging
Basic Try-Catch Structure
try
{
// Code that might cause an error
int result = Divide(10, 0);
}
catch (Exception ex)
{
// What to do if an error happens
Console.WriteLine($"Error: {ex.Message}");
}
Common Exception Types
| Exception Type | When It Occurs |
|---|---|
| DivideByZeroException | Dividing a number by zero |
| NullReferenceException | Trying to use a null object |
| FileNotFoundException | Trying to open a file that doesn't exist |
| IndexOutOfRangeException | Accessing an array element that doesn't exist |
| FormatException | Invalid format when converting data |
Example of Handling Different Exceptions
try
{
int[] numbers = {1, 2, 3};
Console.WriteLine(numbers[5]); // This will cause an error
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("You tried to access an invalid array index");
}
catch (Exception ex)
{
Console.WriteLine($"Some other error occurred: {ex.Message}");
}
Finally Block
The finally block contains code that will always run, whether an exception occurs or not. It's perfect for cleanup tasks.
try
{
// Code that might cause an error
File.OpenRead("nonexistent.txt");
}
catch (FileNotFoundException ex)
{
Console.WriteLine("File not found: " + ex.Message);
}
finally
{
// This code always runs
Console.WriteLine("Cleanup completed");
}
Real-life Analogy
Think of the finally block like cleaning up after cooking. Whether your meal was successful or you burned it, you still need to wash the dishes and put things away.
Throwing Exceptions
You can also create your own exceptions when something goes wrong in your code.
public int Divide(int a, int b)
{
if (b == 0)
{
throw new DivideByZeroException("Cannot divide by zero");
}
return a / b;
}
// Using the method
try
{
int result = Divide(10, 0);
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
}
When to Throw Exceptions:
- When method receives invalid arguments
- When an operation cannot be completed
- When an object is in an invalid state