Subscribe to our YouTube Channel for more Videos

Exception Filters in C# 6.0


C# 6.0 Features Series

C# 6.0 supports a new features called Exception filter that lets the developers to catch the specified exception only if the condition is true.

The Exception filters was a feature in VB and F# and now this feature is brought in to C#.

The Exception filter lets the developers to filter exception by including the if statement immediately after the catch expression. If the result is true then the expression exception is caught.

Below is a sample code snippet demonstrating the usage of the Exception filters in C# 6.0

Imagine a simple situation where you want to throw the Null Pointer exception only on Weekdays . If it is a Weekend , you do not want to catch the exception. Here’s how we do it with exception filters.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Console;
namespace MobileOSGeekApp
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int? input = null;
                ProcessData(input);
            }
            catch (ArgumentNullException exception) if (DateTime.Now.DayOfWeek != DayOfWeek.Saturday || DateTime.Now.DayOfWeek != DayOfWeek.Sunday)
            {
                Console.WriteLine(exception);
            }

        }
        public static int ProcessData(int ? input)
        {
            if (input == null)
                throw new ArgumentNullException(nameof(input));
            return (input.Value + 1);
        }
    }
}

Senthil Kumar B
Senthil Kumar is a former Microsoft MVP (Most Valuable Professional). He is a Co-Author of the book "Windows 10 Development Recipes using JavaScript and CSS" for Apress Publication. He is a technical presenter, blogger, mentor and a Geek.  Senthil is a regular speaker is various local user groups. He has presented at conferences like Great Indian Developer Summit (GIDS) & Microsoft DevCamps. You can reach out to him via his Twitter handle @isenthil.