C# Exception Filters

In C# 6.0, a new feature was introduced which allowed the execution of catch blocks, based on a specific condition when an exception occurs. This means, in a try-catch block, with multiple catch blocks, we can decide which catch block should get executed based on our requirement. 
 
This can be implemented easily by adding the where condition along with the catch blocks. For example, in the following code, we can force the execution of first catch block, if the value of i is greater than 5. Else, it will execute the second block.  
  1. static void Main(string[] args)  
  2.        {  
  3.            int i = 5;  
  4.            try  
  5.            {  
  6.                int a = 0;  
  7.                int b = 5;  
  8.                int c = b / a;  
  9.            }  
  10.            catch (Exception) when (i > 5)  
  11.            {  
  12.                throw;  
  13.            }  
  14.            catch (Exception) when (i <= 5)  
  15.            {  
  16.                throw;  
  17.            }  
  18.            Console.ReadKey();  
  19.        }  
Run the application and see the result.

 

Simple, easy to use, and very helpful feature. Happy coding...!!! 

Up Next
    Ebook Download
    View all
    Learn
    View all