This blog post is part of C# 6.0 Features Series.C# 6.0 contains lots of small features and one of them is Exception filters. It is already there with VB.NET earlier but now it is available in C# also. In exception filters now if exception is combined with Exception statement and If condition of if satisfy then it will execute that block.
Let’s take a simple example to understand it better. Following is a code for a simple console application. Before exception filters we were able to write a code like following.
using System; namespace ExceptionFilters { class Program { static void Main(string[] args) { try { throw new Exception("Jalpesh"); } catch (Exception ex) { if(ex.Message =="Jalpesh") Console.WriteLine("Exception with Message Jalpesh is executed"); else Console.WriteLine("Exception with Message DotNetJalps executed"); } } } }In above example, I have thrown a exception in try block and in catch block I have written if-else block to check message and based on that it will print some method.
This is a old way of doing this. New way is to use If statement with exception block itself.
Following is a code for the same.
using System; namespace ExceptionFilters { class Program { static void Main(string[] args) { try { throw new Exception("Jalpesh"); } catch (Exception ex) if (ex.Message == "Jalpesh") { Console.WriteLine("Exception with Message Jalpesh is executed"); } catch (Exception ex) if (ex.Message == "DotNetJalps") { Console.WriteLine("Exception with Message DotNetJalps executed"); } } } }So If you see the example I have written two exception block with if statement. Now when you run this application and it will show message as expected.
That’s it. Hope you like it. Stay tuned for more!!
Note: You can find all example of C# 6.0 new features at following github location.
https://github.com/dotnetjalps/Csharp6NewFeatures
0 comments:
Post a Comment
Your feedback is very important to me. Please provide your feedback via putting comments.