C# Exception Filters

C# Exception Filters is a feature of C# programming language. It is introduced in version C# 6.0. It allows us to specify condition along with a catch block.

C# provides when keyword to apply a condition (or filter) along with catch block.

A catch block will execute only when the condition is true. If the condition is false, catch block is skipped and compiler search for next catch handler.

C# Exception Filters is used for logging purpose.

C# Exception Filter Syntax

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

In the following example, we are implementing exception filter. It executes only, if compiler throws an IndexOutOfRangeException exception.

C# Exception Filter Example

  1. using System;  
  2. namespace CSharpFeatures  
  3. {  
  4.     class ExceptionFilter  
  5.     {  
  6.         public static void Main(string[] args)  
  7.         {  
  8.             try  
  9.             {  
  10.                 int[] a = new int[5];  
  11.                 a[10] = 12;  
  12.             }catch(Exception e) when(e.GetType().ToString() == "System.IndexOutOfRangeException")  
  13.             {  
  14.                 // Executing some other task  
  15.                 SomeOtherTask();  
  16.             }  
  17.         }  
  18.         static void SomeOtherTask()  
  19.         {  
  20.             Console.WriteLine("A new task is executing...");  
  21.         }  
  22.     }  
  23. }  

Output

A new task is executing...

In the following example, we are throwing exception explicitly that matches with when condition.

C# Exception Filter Example2

  1. using System;  
  2. namespace CSharpFeatures  
  3. {  
  4.     class ExceptionFilter  
  5.     {  
  6.         public static void Main(string[] args)  
  7.         {  
  8.             try  
  9.             {  
  10.                 // Throwing Exception explicitly  
  11.                 throw new IndexOutOfRangeException("Array Exception Occured");  
  12.             }catch(Exception e) when(e.Message == "Array Exception Occured")  
  13.             {  
  14.                 Console.WriteLine(e.Message);  
  15.                 SomeOtherTask();  
  16.             }  
  17.         }  
  18.         static void SomeOtherTask()  
  19.         {  
  20.             Console.WriteLine("A new task is executing...");  
  21.         }  
  22.     }  
  23. }  

Output

Array Exception Occured
A new task is executing...

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

C# Extension Method