Day 25 of 30-Day .NET Challenge: Use Exception Filters
Tags: csharp, dotnet, beginners, programming
Published: 2024-04-15 06:17:00

Learn to enhance your C# code’s readability by avoiding multiple catch blocks. Discover a better approach using Exception Filters on Day 25 of our 30-Day .NET Challenge.

## Introduction

The article demonstrates the use of exception filters to improve the readability, maintainability and performance of the application.

### Learning Objectives

* The problem with traditional exception handling

* Efficient exception handling using filters.

### Prerequisites for Developers

* Basic understanding of C# programming language.

[30 Day .Net Challenge](https://singhsukhpinder.medium.com/list/52a751260fe1)

## Getting Started

### The problem with traditional exception handling

Traditionally, developers often use simple catch blocks to handle exceptions and use conditional logic to handle specific exception types. Please find below the code snippet demonstrating the traditional approach
```csharp
    try
    {
        // Perform an operation
    }
    catch (Exception ex)
    {
        if (ex is InvalidOperationException || ex is ArgumentNullException)
        {
            // Handle the specific exceptions
        }
        else
        {
            throw;  // Rethrow the exception if it's not one we're specifically handling
        }
    }
```
Using conditional statements with an if block creates a code which is hard to maintain and doesn’t look very readable.

### Efficient exception handling using filters

Please find below the refactored version of the previous code snippet
```csharp
    try
    {
        // Perform an operation
    }
    catch (Exception ex) when (ex is InvalidOperationException || ex is ArgumentNullException)
    {
        // Handle only InvalidOperationException or ArgumentNullException
    }
```
The approach above improves the readability and maintainability of the code. In addition to that, it enhances the performance as the catch block is executed only when the filter evaluates to be true as catching an exception is an expensive operation. Only when the filter returns a true, the stack trace will be captured,

## Complete Code

Create another class named ExceptionFilters and add the following code snippet
```csharp
    public static class ExceptionFilters
    {
        public static void MultipleCatch(string input)
        {
            try
            {
                ProcessInput(input);
            }
            catch (Exception ex)
            {
                if (ex is InvalidOperationException || ex is ArgumentNullException)
                {
                    Console.WriteLine($"Conventional Handling: Caught {ex.GetType().Name}");
                }
                else
                {
                    throw;
                }
            }
        }
        public static void GoodWay(string input)
        {
            // Using exception filters
            try
            {
                ProcessInput(input);
            }
            catch (Exception ex) when (ex is InvalidOperationException || ex is ArgumentNullException)
            {
                Console.WriteLine($"Exception Filters Handling: Caught {ex.GetType().Name}");
            }
        }
    
        public static void ProcessInput(string input)
        {
            if (input == null)
                throw new ArgumentNullException(nameof(input), "Input cannot be null.");
            else if (input == "invalid")
                throw new InvalidOperationException("Invalid input provided.");
    
            Console.WriteLine($"Processing {input}");
        }
    }
```
## Execute from the main method as follows
```csharp
    #region Day 25: Use Exception Filters
    static string ExecuteDay25()
    {
        // Using conventional exception handling
        // This will cause ArgumentNullException
        ExceptionFilters.MultipleCatch(null);
    
    
        // Reset input for valid processing
        ExceptionFilters.GoodWay("Valid input");
    
    
        // This input will cause InvalidOperationException
        ExceptionFilters.GoodWay("invalid");
    
        return "Executed Day 25 successfully..!!";
    }
    
    #endregion
```
## Console Output
```
    Conventional Handling: Caught ArgumentNullException
    Processing Valid input
    Exception Filters Handling: Caught InvalidOperationException
```
## Complete Code on GitHub
[GitHub — ssukhpinder/30DayChallenge.Net](https://github.com/ssukhpinder/30DayChallenge.Net/tree/main)

### C# Programming🚀

Thank you for being a part of the C# community! Before you leave:

Follow us: [Youtube](https://www.youtube.com/channel/UCejYGg4gAOa1uPAObFuk1HQ) | [X](https://twitter.com/sukhsukhpinder) | [LinkedIn](https://www.linkedin.com/in/sukhpinder-singh/) | [Dev.to](https://dev.to/ssukhpinder) 
Visit our other platforms: [GitHub](https://github.com/ssukhpinder) 
More content at [C# Programming](https://medium.com/c-sharp-progarmming)