Exception filters - C# 6 Language New features

Exception Handling is one of C# powerful feature. Using try-catch you can easily handle any kind of exception in your application. Also, you can trace different kind of exception by passing different kind of exception type parameter in catch block.

Exception filter is already exists in VB.NET and F#. Microsoft brought this great feature in C# 6.0. In this article we are going to discuss "use of Exception Filters" in C# 6.0. Exception filters allows to specify conditions along with catch block. Catch block will only execute if condition satisfied.

catch (Exception ex) when (conditions)
I took a simple example that throw new exception, having message text 1. when I will run this code, as a default behavior catch block will handle the exception. As per C# 6 new feature I put condition on each catch block. Let's see what happen when I execute this code.

   throw new Exception("1");
catch (Exception e) when (e.Message == "0")
   Console.WriteLine("This is 0 block");
catch (Exception e) when(e.Message =="1")
   Console.WriteLine("This is 1 block");
catch (Exception e) when (e.Message == "2")
   Console.WriteLine("This is 2 block");

When I run this code, as below image, It will match and execute the catch block having condition e.Message ==1. Though We can achieve same using if-else conditions within single catch block. but C# 6.0 make that things easier.

Don't forgot to read my C# 6 language new features series


Popular posts from this blog

12 opensource and free asp.net MVC gridview contols

Scheduling background jobs using Hangfire in ASP.NET Core

Difference ExecuteNonQuery vs ExecuteScalar vs ExecuteReader in asp.net