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

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...