Exception Filters in C# 6.0

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);
        }
    }
}

Leave A Reply

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

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...