Click here to Skip to main content
15,122,251 members
Articles / General Programming / Exceptions
Tip/Trick
Posted 5 May 2015

Stats

17.8K views
40 downloads
15 bookmarked

Exception Filtering: A New Feature of C# 6.0

Rate me:
Please Sign up or sign in to vote.
3.86/5 (3 votes)
5 May 2015CPOL3 min read
In this tip, you will learn the new feature of C# 6.0, Exception Filtering.

Introduction

On the day of the Visual Studio Connect() event held on November 12, 2014, Microsoft introduced Visual Studio 2015 Preview with many new and exciting features for developers including the open source community and .NET 4.6 preview that are released for testing purposes. You can easily download the Visual Studio Preview 2015 from here.

So far, this is the first preview version of Visual Studio 2015 available to download and we hope it will become better in the future. So don't wait to try out this new release and help Microsoft to provide us the final release of the Visual Studio 2015 IDE as soon as possible and don't forget to submit your valuable feedback to Microsoft about your experience with Visual Studio 2015 Preview.

Getting to C#, C# 6.0 brought a set of very useful features with Visual Studio 2015 Preview and .NET 4.6. Let's have a look at one of the features, Exception Filter.

Exception Filtering

An Exception Filter is a feature already present in Visual Basic and F#. Microsoft now introduced this feature in C# 6.0 for developers to use in their code. Exception filters allow you to specify a conditional clause for each catch block. To use exception filters, we need to declare them in the same line as where the catch block is declared, just like this: catch ( Exception e) if(filtercondition). Instead of a catch block handling all exceptions of a specific type, they allow us to write catch blocks that handle when a certain condition is true. If the parenthesized expression after the "if" condition evaluates to true, the catch block will be executed, else the exception continues. Catching and rethrowing are preferred using exception filters because they leave the stack unharmed and if the exception later causes the stack to be dumped, we can see where it originated from.

Check out the following code snippet to understand how to write the Expression Filters in a catch statement of any try {} catch {} block.

C#
try
{
   int number = 0;
   int x = 5 / number;
}
catch (DivideByZeroException) if (DateTime.Now.DayOfWeek != DayOfWeek.Tuesday)
{
   Console.WriteLine("Sorry, today is not Tuesday");
}
catch (DivideByZeroException) if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
{
   Console.WriteLine("Hurray It's Tuesday");
}

In the preceding code snippet, the try block is generating the exception DivideByZeroException and we have defined two DivideByZeroException catch blocks with different conditions. In the first condition, we are checking if the present day is not Tuesday, then the catch block will be executed and "Sorry, today is not Tuesday" will be printed. And in the second DivideByZeroException catch block, we are checking if today's day is Tuesday and if so, then the second catch block will be executed and "Hurray It's Tuesday" will be printed.

Demo Application using Visual Studio 2013

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpFeatures
{
    class ExceptionFilters
    {
        static void Main(String[] args)         //using Visual Studio 2013
        {
            try
            {
                int number = 0;
                int x = 5 / number;
            }
            catch (DivideByZeroException)
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
                {
                    Console.WriteLine("Yes it is Tuesday");
                }
                else
                {
                    Console.WriteLine("No its not tuesday");
                }
            }
            Console.WriteLine("Press any key to exit..");
            Console.Read();
        }
    }
}

Demo Application using Visual Studio 2015 Preview

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CSharpFeatures
{
    class ExceptionFilters
    {
        static void Main(String[] args)         //using Visual Studio 2015
        {
            try
            {
                int number = 0;
                int x = 5 / number;
            }
            catch (DivideByZeroException) if (DateTime.Now.DayOfWeek != DayOfWeek.Tuesday)
            {
                Console.WriteLine("Sorry, today is not Tuesday");
            }
            catch (DivideByZeroException) if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
            {
                Console.WriteLine("Hurray It's Tuesday");
            }
            Console.WriteLine("Press any key to exit");
            Console.Read();
        }
    }
}

Summary

In this tip, we learned how to use exception filtering in catch statements of any try {} catch {} block. That means that without catching the exception, we are checking for a condition and if the condition is not met, the next catch block is considered.

So, what's your opinion about this feature? How will you use it in your project? Your comments are most welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

arora.abhishek
Tester / Quality Assurance
India India
Hello this is Abhishek working as a Software Test Engineer

Comments and Discussions

 
QuestionIf is now when Pin
danie_lidstrom25-Sep-15 2:30
Memberdanie_lidstrom25-Sep-15 2:30 
Questioncarlos llanos Pin
Member 105265999-Jun-15 16:52
professionalMember 105265999-Jun-15 16:52 
QuestionBasically just a move of the if... statement, BUT! Pin
Mike Barthold6-May-15 8:55
professionalMike Barthold6-May-15 8:55 
QuestionOn the feature in general Pin
jfriedman6-May-15 3:41
Memberjfriedman6-May-15 3:41 
Good Article.

IMHO the feature is fairly useless, just like the null coalescing operator or primary constructors Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.