πŸ”Ÿ C# File and Exception Handling
Estimated reading: 3 minutes 359 views

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, and throw
  • 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:

KeywordPurpose
tryEncapsulates code that may throw an exception
catchHandles the exception
finallyExecutes cleanup code, regardless of exception
throwRaises 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 try causes an exception.
  • catch catches DivideByZeroException and 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:

  • finally ensures 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:

  • throw is 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-finally to 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 :
Share

πŸ’Ύ C# Exception Handling

Or Copy Link

CONTENTS
Scroll to Top