C# 6.0–Exception Filters

This blog post is part of C# 6.0 Features Series.
C# 6.0 contains lots of small features and one of them is Exception filters. It is already there with VB.NET earlier but now it is available in C# also. In exception filters now if exception is combined with Exception statement and If condition of if satisfy then it will execute that block.

Let’s take a simple example to understand it better. Following is a code for a simple console application. Before exception filters we were able to write a code like following.
using System;

namespace ExceptionFilters
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("Jalpesh");
            }

            catch (Exception ex)
            {
                if(ex.Message =="Jalpesh")
                    Console.WriteLine("Exception with Message Jalpesh is executed");
                else
                    Console.WriteLine("Exception with Message DotNetJalps executed");
            }
        }
    }
}
In above example, I have thrown a exception in try block and in catch block I have written if-else block to check message and based on that it will print some method.


This is a old way of doing this. New way is to use If statement with exception block itself.
Following is a code for the same.
using System;

namespace ExceptionFilters
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                throw new Exception("Jalpesh");
            }
            catch (Exception ex) if (ex.Message == "Jalpesh")
            {
                Console.WriteLine("Exception with Message Jalpesh is executed");
            }
            catch (Exception ex) if (ex.Message == "DotNetJalps")
            {
                Console.WriteLine("Exception with Message DotNetJalps executed");
            }
        }
    }
}
So If you see the example I have written two exception block with if statement. Now when you run this application and it will show message as expected.

exception-filter-csharp6

That’s it. Hope you like it. Stay tuned for more!!

Note: You can find all example of C# 6.0 new features at following github location.
https://github.com/dotnetjalps/Csharp6NewFeatures

Comments

Popular posts from this blog

How to create Rest API(Web API) with ASP.NET Core 1.0

Creating PDF with ASP.Net MVC and RazorPDF

Solution: gulp is not recognized as internal or external command- Visual Studio