C# Exception Handling β Mastering Try, Catch, and Finally
Introduction β Why Learn C# Exception Handling?
In real-world C# programming, unexpected conditionsβsuch as missing files, division by zero, or invalid inputsβcan crash your program if not handled properly. That’s where C# exception handling comes in.
It allows you to detect, manage, and recover from errors without disrupting the flow of your applicationβessential for creating robust, user-friendly software.
In this guide, you’ll learn:
- The fundamentals of exception handling in C#
- How to use
try,catch,finally, andthrow - Custom exception creation
- Common best practices and pitfalls
Core Concept β What Is Exception Handling in C#?
Exception Handling is the process of responding to the occurrence of runtime anomalies (exceptions).
C# uses a structured model involving four keywords:
| Keyword | Purpose |
|---|---|
try | Encapsulates code that may throw an exception |
catch | Handles the exception |
finally | Executes cleanup code, regardless of exception |
throw | Raises an exception manually |
Code Examples β With Step-by-Step Explanations
1. Basic Try-Catch Example
try
{
int x = 10;
int y = 0;
int result = x / y; // Division by zero
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero!");
}
Explanation:
- The code inside
trycauses an exception. catchcatchesDivideByZeroExceptionand handles it gracefully.
2. Using Finally
StreamReader reader = null;
try
{
reader = new StreamReader("data.txt");
Console.WriteLine(reader.ReadToEnd());
}
catch (FileNotFoundException)
{
Console.WriteLine("File not found.");
}
finally
{
if (reader != null)
reader.Close();
}
Explanation:
finallyensuresreader.Close()is called even if an exception is thrown.
3. Throwing Custom Exceptions
public void ValidateAge(int age)
{
if (age < 0)
throw new ArgumentException("Age cannot be negative.");
}
Explanation:
throwis used to raise an exception when a condition fails.
4. Multiple Catch Blocks
try
{
int[] arr = new int[3];
Console.WriteLine(arr[5]); // IndexOutOfRangeException
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Array index is out of bounds!");
}
catch (Exception ex)
{
Console.WriteLine("General exception: " + ex.Message);
}
Explanation:
- Catches specific exceptions first, then a general fallback.
Best Practices & Tips
Best Practice: Catch the most specific exceptions first, then the general Exception.
Tip: Use finally for closing resources like files, streams, or database connections.
Pitfall: Donβt use empty catch blocks β always log or handle the exception.
Exception Hierarchy (Simplified)
System.Exception
βββ System.SystemException
β βββ DivideByZeroException
β βββ IndexOutOfRangeException
β βββ InvalidCastException
βββ System.IO.IOException
β βββ FileNotFoundException
βββ System.ApplicationException
Real-World Use Cases
- Handling missing or corrupt files (
FileNotFoundException) - Validating user inputs (
ArgumentException) - Managing database and API errors (
SqlException,HttpRequestException) - Network retries and fallback logic
Summary β Recap & Next Steps
C# exception handling ensures your program remains stable and responsive, even under unexpected conditions.
Key Takeaways:
- Use
try-catch-finallyto manage runtime errors - Always handle specific exceptions before general ones
- Avoid hiding exceptions β log or report them
Next Up: Explore throw vs throw ex, AggregateException in async, and logging frameworks.
FAQ Section
What’s the difference between throw and throw ex?
throw preserves the original stack trace. throw ex resets itβavoid throw ex.
Can you catch multiple exception types in one block?
Yes, using pattern matching in C# 7+:
catch (Exception ex) when (ex is IOException || ex is SocketException)
What happens if an exception is not caught?
The program crashes and displays an unhandled exception message.
Is it mandatory to use finally?
No, but it’s recommended when releasing unmanaged resources.
Can exceptions be nested?
Yes, one exception can contain another via the InnerException property.
Share Now :
