A Responsive Blogger Website, That Take my blog to the next level.

I am a Software Developer, Learning and experementing with .Net Technology and try to put my Learning altogether here.


We have all sections related to .Net Technology, like .Net-C#, Asp.Net, MVC, jQuery, AngularJs, Sharepoint. Find out more...


Following are the some of the Advantages of using this Web site :-

  • Get Update about latest in .Net world.
  • Collection of Useful, Frequently used .Net Solutions.
  • It’s beautiful on every screen size (try resizing your browser!)
by

4. New Features in C# 6.0 - Exception Filter



One of my most favorite features of C# 6.0 is the Exception Filter. This allows an exception to be caught in the CATCH block, only a specified condition is met when the exception is thrown. Prior to C# 6.0, we did not have any mechanism to filter the exception in the catch block. We used the if-else statement in the same catch block to bring some sort of filter. To understand it better, let us consider the listing below:
static void Main(string[] args)
        {
            int number = 28;
            try
            {

                int rem = number / 0;
                WriteLine(rem);
            }
            catch (DivideByZeroException ex)
            {
                Console.WriteLine(ex.Message);
            }
                    
            ReadKey(true);           
        } 
The major problem in the above snippet is that we cannot apply a filter in the catch block. In C# 6.0, the exception filter can be applied as shown in the listing below:

   static void Main(string[] args)
        {
            int number = 24;
            try
            {
                int rem = number % 0;
                WriteLine(rem);
            }
            catch (DivideByZeroException ex) when (ex.Message.Contains("ck"))
            {
               WriteLine(ex.Message);
            }
            catch (DivideByZeroException ex) when (ex.Source == "ConsoleApplication1")
            {
                WriteLine(ex.Source);
            }

            ReadKey(true);
        }

In C#6.0 using “when”, we can filter the exception. In the above snippet in particular, the catch statement will be thrown only when the condition in the when statement is true. The filtering exception could be very useful here.

0 comments :