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)
                int? input = null;
            catch (ArgumentNullException exception) if (DateTime.Now.DayOfWeek != DayOfWeek.Saturday || DateTime.Now.DayOfWeek != DayOfWeek.Sunday)

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

0 thoughts on “Exception Filters in C# 6.0

  1. Pingback: C# 6.0 Features | Ginktage

  2. Pingback: Getter-only (Read Only) Auto Properties in C# 6.0 | Developer Publish

  3. Pingback: Initializers for Read-Only Auto Properties in C# 6.0 | Developer Publish

  4. Pingback: String Interpolation in C# 6.0 | Developer Publish

  5. Pingback: Dictionary Initializers (Index Initializers) in C# 6.0 | Developer Publish

Leave a Reply

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