Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Exception Filtering in C#

Introduction

Exception filtering is a powerful feature in C# that allows you to specify conditions under which an exception will be caught. This can be useful for handling only certain types of exceptions or for adding additional logic when an exception occurs.

Basic Syntax

The basic syntax for exception filtering in C# involves using the when keyword in a catch block. Here's a simple example:

try
{
    // Code that may throw an exception
}
catch (Exception ex) when (ex.Message.Contains("specific condition"))
{
    // Handle exception if condition is met
}
                

Detailed Example

Let's consider a more detailed example to understand how exception filtering works. In this example, we'll try to open a file and handle exceptions differently based on the exception message.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        try
        {
            // Attempt to open a file
            using (StreamReader sr = new StreamReader("nonexistentfile.txt"))
            {
                Console.WriteLine(sr.ReadToEnd());
            }
        }
        catch (FileNotFoundException ex) when (ex.Message.Contains("nonexistentfile.txt"))
        {
            Console.WriteLine("File not found: " + ex.Message);
        }
        catch (IOException ex)
        {
            Console.WriteLine("An I/O error occurred: " + ex.Message);
        }
    }
}
                

In this example, if the file "nonexistentfile.txt" is not found, the first catch block will handle the exception. For other I/O errors, the second catch block will handle them.

Advantages of Exception Filtering

Exception filtering offers several advantages:

  • More granular control over exception handling.
  • Improves readability by consolidating related exception handling logic.
  • Reduces the need for nested try-catch blocks.

Best Practices

When using exception filtering, consider the following best practices:

  • Use specific conditions to filter exceptions to avoid catching unintended exceptions.
  • Keep the filtering logic simple to maintain readability and performance.
  • Avoid using exception filtering for general control flow; it should be used for exceptional conditions.

Conclusion

Exception filtering is a valuable feature in C# that allows you to handle exceptions more precisely. By using the when keyword, you can specify conditions under which an exception will be caught, leading to cleaner and more maintainable code.