Error Handling in C#
Error handling in C# is essential for building robust and reliable programs.
The language provides mechanisms to detect, catch, and respond to unexpected situations using exceptions.
Using try-catch
The try-catch structure allows executing code that might fail and handling the exception in case of an error.
try
{
int number = 10;
int result = number / 0; // Error: division by zero
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero.");
Console.WriteLine($"Details: {ex.Message}");
}
try-catch Flow
- The
tryblock contains the code that may produce an error. - The
catchblock catches and handles the exception. - Optionally, you can use
finallyto execute code regardless of whether an error occurred:
try
{
Console.WriteLine("Trying to open resource...");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
finally
{
Console.WriteLine("Releasing resources...");
}
Common Exceptions in C#
C# provides different exception classes that inherit from System.Exception.
1. System.Exception
This is the base class for all exceptions. It can be caught to handle any generic error.
try
{
throw new Exception("Generic error.");
}
catch (Exception ex)
{
Console.WriteLine($"Exception caught: {ex.Message}");
}
2. System.NullReferenceException
Occurs when attempting to access an object that is null.
string text = null;
try
{
Console.WriteLine(text.Length); // Error: null object
}
catch (NullReferenceException ex)
{
Console.WriteLine("Null reference detected.");
}
3. System.IndexOutOfRangeException
Happens when trying to access an index that doesn't exist in an array or collection.
int[] numbers = { 1, 2, 3 };
try
{
Console.WriteLine(numbers[5]); // Error: index out of range
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range.");
}
4. System.DivideByZeroException
Appears when attempting to divide a number by zero.
try
{
int result = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: division by zero.");
}
Best Practices in Error Handling
- Catch only the necessary exceptions (avoid always using
Exception). - Use descriptive messages to understand the error.
- Release resources in the
finallyblock or withusing. - Avoid silencing exceptions without handling them.