πΎ 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.
- catchcatches- DivideByZeroExceptionand 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:
- finallyensures- reader.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 :
