Exception Filters
Exception Filters

I were discussing the new features introduced in C# 6.0 in my previous blog. One of the new features of C# 6.0 is exception filters. So let’s understand what it is.

Exception filters allows to specify the condition with the catch block. The code looks like below.

            try
            {
                ThrowExceptionTest();
            }
            catch (Exception e) when (e.Message == "Testing Exception Filters")
            {
                WriteLine(e.Message + " has been handled. ");
            }

How it works is simple to predict. Condition will be evaluated before entering to the catch block when exception occurs. Only when condition become true, code in the catch block will be executed. You can put any condition like function call, variable value or virtually any expression that can be evaluate as either true or false (bool) at run time.

We could have achieved the same objective by using if block inside the catch and throw as in below code.

using System;

using static System.Console;  // this is new feature of C# 6.0
namespace NewFeaturesOfCSharp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            WriteLine("Hello");

            try
            {

                //ThrowExceptionTest();
                ThrowAnotherExceptionTest();
            }
            catch (Exception e)
            {
                if (e.Message == "Testing Exception Filters")
                {
                    WriteLine(e.Message + " has been handled. ");
                }
                else
                {
                    WriteLine(e.Message + " will be bubble up. ");
                    throw; 
                }
            }

            try
            {
                // ThrowExceptionTest();
                ThrowAnotherExceptionTest();
            }
            catch (Exception e) when (e.Message == "Testing Exception Filters")
            {
                WriteLine(e.Message + " has been handled. ");
            }
            ReadLine(); 
        }
        public static void ThrowExceptionTest()
        {
            throw new Exception("Testing Exception Filters"); 
        }

        public static void ThrowAnotherExceptionTest()
        {
            throw new Exception("This is another exception");

        }
    }
}

Benefits of Exception Filters

The important thing aspects of using exception filters it that it doesn’t unwind the stake.

Please check out my blog for C# 6.0 features namely compiler as server and using static here.

Please follow and like us:
Exception Filters in C# 6.0

Leave a Reply

Your email address will not be published. Required fields are marked *