πŸ”Ÿ C# File and Exception Handling
Estimated reading: 3 minutes 35 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ’Ύ C# Exception Handling

Or Copy Link

CONTENTS
Scroll to Top