Exception Filters in C# 6.0

So far we deal with exceptions as in the following. As you see in the following code snippet, we are catching the exception and displaying the error message.

  1. using System;  
  2. namespace demo1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.   
  9.             int number = 24;  
  10.             try  
  11.             {  
  12.   
  13.                 int rem = number % 0;  
  14.                 Console.WriteLine(rem);  
  15.             }  
  16.             catch (DivideByZeroException ex)  
  17.             {  
  18.                 Console.WriteLine(ex.Message);  
  19.             }  
  20.   
  21.             Console.ReadKey(true);  
  22.         }  
  23.     }  

The challenge in the preceding snippet is that you cannot apply a filter to the exception. Of course you can have an if-else statement inside the try catch block but it will cause a specific catch block to be executed and then the filter would be applied.

In C# 6.0 a new feature was introduced to apply a filter to a catch block. This feature is known as Exception filters. Now a specific catch block can be executed only of the filter is set to true.



In the preceding snippet we are filtering the exception on various criteria, such as if a message contains a specific string then execute a specific catch block or on the basis of the exception source execute a specific catch block.

This feature may be useful in scenarios in which you need to perform various actions if a condition is met in a specific exception type. For your reference the source code is given below.

  1. using System;  
  2. namespace demo1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.   
  9.             int number = 24;  
  10.             try  
  11.             {  
  12.   
  13.                 int rem = number % 0;  
  14.                 Console.WriteLine(rem);  
  15.             }  
  16.             catch (DivideByZeroException ex) if (ex.Message.Contains("dj"))  
  17.             {  
  18.                 Console.WriteLine(ex.Message);  
  19.             }  
  20.             catch(DivideByZeroException ex) if (ex.Source == "demo1")  
  21.             {  
  22.                 Console.WriteLine(ex.Source);  
  23.             }  
  24.   
  25.             Console.ReadKey(true);  
  26.         }  
  27.     }  

The exception message does not contain any string dj hence the first catch block will not be executed. However the second catch block will be executed since the source of the exception is demo1. You will get the expected output as below:



I hope the concept of the Exception filter is clear to you now and you will harness this C# 6.0 feature in your project.

Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all