Exception Filters - C# Tutorial
C# Course / Exception Handling / Exception Filters

Exception Filters

BLUF: Mastering Exception Filters is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Exception Filters

C# is a powerful, modern language for enterprise solutions. Discover how Exception Filters enhances your development workflow in the guide below.

C# Exception Filters is a functionality in the C# programming language that was first introduced in the C# 6.0 version. This feature enables developers to define a specific condition in conjunction with a catch block.

C# offers the "when" keyword to apply a condition, also known as a filter, in conjunction with the catch block.

A catch block is triggered only if the specified condition evaluates to true. In cases where the condition is false, the catch block is bypassed, and the compiler proceeds to search for the next available catch handler.

C# Exception Filters is used for logging purpose.

C# Exception Filter Syntax

Example

catch (ArgumentException e) when (e.ParamName == "?"){  }

In this instance, we are incorporating an exception filter that will only run if the compiler triggers an exception related to IndexOutOfRangeException.

C# Exception Filter Example

Example

using System;
namespace CSharpFeatures
{
    class ExceptionFilter
    {
        public static void Main(string[] args)
        {
            try
            {
                int[] a = new int[5];
                a[10] = 12;
            }catch(Exception e) when(e.GetType().ToString() == "System.IndexOutOfRangeException")
            {
                // Executing some other task
                SomeOtherTask();
            }
        }
        static void SomeOtherTask()
        {
            Console.WriteLine("A new task is executing...");
        }
    }
}

Output

Output

A new task is executing...

In this instance, we are explicitly raising an exception that aligns with a specific condition.

C# Exception Filter Example2

Example

using System;
namespace CSharpFeatures
{
    class ExceptionFilter
    {
        public static void Main(string[] args)
        {
            try
            {
                // Throwing Exception explicitly
                throw new IndexOutOfRangeException("Array Exception Occured");
            }catch(Exception e) when(e.Message == "Array Exception Occured")
            {
                Console.WriteLine(e.Message);
                SomeOtherTask();
            }
        }
        static void SomeOtherTask()
        {
            Console.WriteLine("A new task is executing...");
        }
    }
}

Output

Output

Array Exception Occured
A new task is executing...

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience