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
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
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
A new task is executing...
In this instance, we are explicitly raising an exception that aligns with a specific condition.
C# Exception Filter Example2
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
Array Exception Occured
A new task is executing...