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