Letβs go through try-catch-finally in C# β essential for exception handling. Also see Common Types of Exceptions.
π 1. What is Exception Handling?
-
Exceptions are runtime errors that disrupt the normal flow of a program.
-
Try-catch-finally allows you to handle errors gracefully instead of crashing the program.
π 2. Basic Syntax
try
{
// Code that might throw an exception
}
catch (ExceptionType e)
{
// Handle the exception
}
finally
{
// Code that always runs, whether exception occurred or not
}
-
try
β Wrap code that might throw an exception -
catch
β Handle the exception -
finally
β Optional; runs always, e.g., for cleanup
π 3. Example: Simple try-catch
try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Index out of range
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
Output:
Error: Index was outside the bounds of the array.
π 4. Catching Multiple Exceptions
try
{
int a = 10, b = 0;
int result = a / b;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
}
catch (Exception ex)
{
Console.WriteLine("Some other error: " + ex.Message);
}
-
Specific exceptions first, then general Exception
-
Avoid catching general exceptions unless necessary
π 5. Finally Block
-
Executes regardless of exception occurrence
-
Useful for cleanup code (closing files, releasing resources)
try
{
Console.WriteLine("Trying risky operation...");
}
catch (Exception ex)
{
Console.WriteLine("Caught an exception: " + ex.Message);
}
finally
{
Console.WriteLine("This always runs!");
}
Output:
Trying risky operation...
This always runs!
π 6. Throwing Exceptions
- You can manually throw exceptions using
throw
void ValidateAge(int age)
{
if (age < 0)
throw new ArgumentException("Age cannot be negative");
}
try
{
ValidateAge(-5);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
π 7. Summary Table
Keyword | Purpose |
---|---|
try | Wrap code that might fail |
catch | Handle specific exceptions |
finally | Execute code regardless of exceptions |
throw | Manually throw an exception |
β Tips:
-
Always catch specific exceptions first
-
Use finally to release resources
-
Donβt overuse empty catch blocks β handle or log errors properly