C sharp - Exception Handling in C#.
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
-
Code that may cause an exception goes inside a
tryblock.
try
{
int x = 10;
int y = 0;
int result = x / y; // This will throw a DivideByZeroException
}
catch
-
If an exception occurs in the
tryblock, execution jumps to thecatchblock. -
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
finallyblock 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
-
Used to manually raise an exception.
-
You can throw built-in exceptions or create custom ones.
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
-
tryblock executes. -
If an exception occurs:
-
Control jumps to the matching
catch. -
If no
catchmatches, the program crashes.
-
-
finallyexecutes 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
finallyfor cleanup (files, database connections, etc.). -
Don’t overuse exceptions for normal logic flow.