paint-brush
The 30-Day .NET Challenge - Day 25: Use Exception Filtersby@ssukhpinder
155 reads

The 30-Day .NET Challenge - Day 25: Use Exception Filters

by Sukhpinder SinghApril 15th, 2024
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

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. The article demonstrates the use of exception filters to improve the readability, maintainability and performance of the application.
featured image - The 30-Day .NET Challenge - Day 25: Use Exception Filters
Sukhpinder Singh HackerNoon profile picture

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

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.

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 that 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

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” will the stack trace will be captured,

Complete Code

Create another class named ExceptionFilters and add the following code snippet.

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

#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

C# Programming🚀

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

Follow us: Youtube | X | LinkedIn | Dev.to

Visit our other platforms: GitHub

More content at C# Programming


Also published here.