C# > Advanced C# > Exception Handling > Using System.Exception

Exception Filters for Specific Exception Handling

This snippet showcases the use of exception filters in C# to handle specific exceptions based on certain conditions. Exception filters provide a way to inspect an exception and decide whether or not to execute the associated catch block.

Code Snippet

This code demonstrates the use of exception filters using the `when` keyword in the `catch` block. The `HandleInput` method attempts to parse a string into an integer. If the input is null or empty, it throws an `ArgumentNullException`. If the input is not a valid integer, it throws a `FormatException`. The `Main` method catches these exceptions, but only executes the catch block if the condition specified in the `when` clause is met. For example, the `FormatException` catch block only executes if the exception message contains the word 'invalid'. The `ArgumentNullException` catch block executes only if the parameter name is equal to 'input'. Exception filters allow for fine-grained control over exception handling, making it possible to handle specific cases while still providing a general catch-all for unexpected exceptions.

using System;

public class Example
{
    public static void Main(string[] args)
    {
        try
        {
            // Simulate different error conditions
            HandleInput("invalid"); // Throws FormatException
            HandleInput(null);      // Throws ArgumentNullException
        }
        catch (FormatException ex) when (ex.Message.Contains("invalid"))
        {
            Console.WriteLine("FormatException caught: Invalid input format.");
        }
        catch (ArgumentNullException ex) when (ex.ParamName == "input")
        {
            Console.WriteLine("ArgumentNullException caught: Input cannot be null.");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"General Exception caught: {ex.Message}");
        }
    }

    public static void HandleInput(string input)
    {
        if (string.IsNullOrEmpty(input))
        {
            throw new ArgumentNullException("input", "Input cannot be null or empty.");
        }

        try
        {
            int number = int.Parse(input);
            Console.WriteLine($"Parsed number: {number}");
        }
        catch (FormatException)
        {
            throw;
        }
    }
}

Concepts Behind the Snippet

Exception filters provide a powerful mechanism for handling specific exception scenarios based on properties of the exception object. By using the `when` keyword, you can add a boolean expression to a `catch` block that determines whether the catch block should execute. This allows you to inspect the exception object (e.g., its message, type, or properties) and make a decision about how to handle it. This approach reduces code duplication and improves the readability of exception handling logic.

Real-Life Use Case

Consider a scenario where you are processing data from multiple sources. You might receive `IOException` exceptions due to various reasons, such as file not found, permission denied, or disk full. Using exception filters, you can differentiate between these scenarios and handle them accordingly. For example, you might retry reading a file if the exception is due to a temporary network issue, but log an error and skip the file if the exception is due to insufficient permissions.

Best Practices

  • Use exception filters for specific cases: Use exception filters when you need to handle exceptions differently based on specific properties of the exception object.
  • Keep filter conditions simple: Complex filter conditions can make the code harder to read and maintain. If the filter logic is complex, consider extracting it into a separate method.
  • Avoid side effects in filter conditions: Filter conditions should not modify the state of the application. They should only inspect the exception object.
  • Always include a general catch block: Provide a general catch block to handle unexpected exceptions that are not handled by the specific filters.

Interview Tip

When discussing exception filters in interviews, explain how they provide a way to handle exceptions based on specific conditions. Highlight the benefits of using exception filters, such as reduced code duplication and improved readability. Be prepared to discuss the limitations of exception filters and the importance of avoiding side effects in filter conditions.

When to Use Them

Exception filters are particularly useful when you need to handle different variations of the same exception type. For instance, you might have different ways of handling a `SqlException` based on the error code or the severity of the error. Exception filters allow you to write different `catch` blocks for each scenario. Also, use exception filters to implement retry logic without having to catch and re-throw exceptions.

Memory Footprint

The memory footprint of exception filters is minimal. The main impact is the slight performance cost associated with evaluating the filter condition. This cost is usually negligible compared to the benefits of more precise exception handling.

Alternatives

The alternative to using exception filters is to catch the exception and then use `if` statements to determine how to handle it. This approach can lead to code duplication and make the code harder to read. Another alternative is to create custom exception classes for each scenario, but this can increase the complexity of the code and make it harder to maintain.

Pros

  • Improved code readability: Exception filters make the code easier to read by separating the exception handling logic into different catch blocks based on specific conditions.
  • Reduced code duplication: Exception filters reduce code duplication by allowing you to handle different variations of the same exception type in different catch blocks.
  • Fine-grained control: Exception filters provide fine-grained control over exception handling, allowing you to handle specific cases while still providing a general catch-all for unexpected exceptions.

Cons

  • Increased complexity: Exception filters can make the code more complex if the filter conditions are complex.
  • Potential performance overhead: Evaluating the filter condition can introduce a slight performance overhead.

FAQ

  • What is an exception filter?

    An exception filter is a boolean expression that is evaluated when an exception is caught. The catch block is only executed if the filter expression evaluates to true.
  • How do I use exception filters?

    You use exception filters by adding a `when` clause to a catch block. The `when` clause specifies the filter expression.
  • Can I use multiple exception filters?

    Yes, you can use multiple exception filters in the same try-catch block. Each catch block can have its own filter condition.