Exception Filtering in C# 6.0

Those of you who read my previous post on “What’s new in C# 6.0” may have noticed that I forget to discuss an important feature of C# 6.0. Well that is exception filtering. I thought about updating the previous post with this feature explained but again felt that it deserves a post of its own. So let's start.

Exception Filtering

Exception filtering is nothing but some condition attached to the catch block. Execution of the catch block depends on this condition. Let me give you a simple example.

In C# 5, we would have done something like the code given below to show users appropriate messages depending on the randomly generated http status codes.

  1. using System;  
  2. using static System.Console;  
  3.   
  4. namespace NewInCSharp  
  5. {  
  6.     class Program  
  7.     {  
  8.         private static void Main(string[] args)  
  9.         {  
  10.             Random random = new Random();  
  11.             var randomExceptions = random.Next(400, 405);  
  12.             WriteLine("Generated exception: " + randomExceptions);  
  13.             Write("Exception type: ");  
  14.   
  15.             try  
  16.             {  
  17.                 throw new Exception(randomExceptions.ToString());  
  18.             }  
  19.             catch (Exception ex)  
  20.             {  
  21.                 if(ex.Message.Equals("400"))  
  22.                     Write("Bad Request");  
  23.                 else if (ex.Message.Equals("401"))  
  24.                     Write("Unauthorized");  
  25.                 else if (ex.Message.Equals("402"))  
  26.                     Write("Payment Required");  
  27.                 else if (ex.Message.Equals("403"))  
  28.                     Write("Forbidden");  
  29.                 else if (ex.Message.Equals("404"))  
  30.                     Write("Not Found");  
  31.             }  
  32.   
  33.             ReadLine();  
  34.         }  
  35.     }  
  36. }  
Here, I am randomly generating an exception code randomExceptions. Inside the catch block I'm showing appropriate error message respective to the exception code.

Now you can achieve the same thing using exception filtering but the syntax is bit different. Rather than entering the catch block and check to see which condition met our exception, we can now decide that we even want to enter the specific catch block. Here is the code,
  1. using System;  
  2. using static System.Console;  
  3.   
  4. namespace NewInCSharp  
  5. {  
  6.     class Program  
  7.     {  
  8.         private static void Main(string[] args)  
  9.         {  
  10.   
  11.             Random random = new Random();  
  12.             var randomExceptions = random.Next(400, 405);  
  13.             WriteLine("Generated exception: " + randomExceptions);  
  14.             Write("Exception type: ");  
  15.   
  16.             try  
  17.             {  
  18.                 throw new Exception(randomExceptions.ToString());  
  19.             }  
  20.             catch (Exception ex) when (ex.Message.Equals("400"))  
  21.             {  
  22.                 Write("Bad Request");  
  23.                 ReadLine();  
  24.             }  
  25.             catch (Exception ex) when (ex.Message.Equals("401"))  
  26.             {  
  27.                 Write("Unauthorized");  
  28.                 ReadLine();  
  29.             }  
  30.             catch (Exception ex) when (ex.Message.Equals("402"))  
  31.             {  
  32.                 Write("Payment Required");  
  33.                 ReadLine();  
  34.             }  
  35.             catch (Exception ex) when (ex.Message.Equals("403"))  
  36.             {  
  37.                 Write("Forbidden");  
  38.                 ReadLine();  
  39.             }  
  40.             catch (Exception ex) when (ex.Message.Equals("404"))  
  41.             {  
  42.                 Write("Not Found");  
  43.                 ReadLine();  
  44.             }  
  45.         }  
  46.     }  
  47. }  
So, what's the main difference between these two. Well when you enter a catch block, the current execution state is lost. So, the actual cause of the exception is really hard to find. But in the exception filtering we stay where we should be staying i.e. current execution state. This means the stack stays unharmed.
 
So, exception filtering is good, right? Well there is a catch! Since in the exception filtering, entering a catch block depends on the filter applied on the catch, making a silly mistake can change the whole meaning of the exception. This may actually happen because the filtering depends on a boolean result and this boolean result can be sent from any code block, making the exception has a different meaning. For example,
  1. using System;  
  2. using System.Net.Http;  
  3. using System.Threading.Tasks;  
  4. using static System.Console;  
  5.   
  6. namespace NewInCSharp  
  7. {  
  8.     class Program  
  9.     {  
  10.        private static void Main(string[] args)  
  11.         {  
  12.             Task.Factory.StartNew(GetWeather);  
  13.             ReadLine();  
  14.         }  
  15.   
  16.         private static async void GetWeather()  
  17.         {  
  18.             string customErrorMessage;  
  19.             HttpClient client = new HttpClient();  
  20.   
  21.             try  
  22.             {  
  23.                 HttpResponseMessage httpResponseMessage = await client.GetAsync("http://api.openweathemap.org/data/2.5/weather?q=NewYorK");  
  24.                 WriteLine(httpResponseMessage);  
  25.             }  
  26.             catch (Exception ex) when (DoASillyMistake(ex.Message, out customErrorMessage))  
  27.             {  
  28.                 WriteLine(customErrorMessage);  
  29.             }  
  30.         }  
  31.   
  32.         private static bool DoASillyMistake(string exceptionMessage, out string customErrorMessage)  
  33.         {  
  34.             if (exceptionMessage.Equals("An error occurred while sending the request."))  
  35.             {  
  36.                 customErrorMessage = "Unauthorized.";  
  37.                 return true;  
  38.             }  
  39.             else  
  40.             {  
  41.                 customErrorMessage = "Bad Gateway.";  
  42.                 return true;  
  43.             }  
  44.         }  
  45.     }  
  46. }  
This is a silly example I must say, but let's assume that if a request to a weather service fails, its because of two reasons, one the service is not up and running [Bad Request] and the second is a user needs to be authorized before accessing the service [Unauthorized]. So, in my code I know for sure that the HttpClient will throw an error message like below if it's a Bad Request.

An error occurred while sending the request.

Again for any other error messages, let's assume it's an Unauthorized request. If you look carefully at the DoASillyMistake(string exceptionMessage, out string customErrorMessage) function, you will see I really did a silly mistake. I've shown the user that they are 'Unauthorized' to access the service while the message should be 'Bad Request' since the service url is not valid [there is a letter missing in the url; 'r' to complete the word weather]. Now the funny and bit irritating part is user will now start looking for a registration process to get access to the service. But sadly we all know that not the case. More funny part is even if he registered himself, from now he will get a 'Bad Request'. So you must be careful when using exception filtering.

But even this side effect can sometimes come in handy. For example, you can attach a filter function which logs error messages and returns false so that the log contains an appropriate exception and also the execution cursor doesn't end up in the catch block. Here is a good example which I found in this open source dotnet git repo documentation, New Language Features in C# 6.
  1. private static bool Log(Exception e) { /* log it */ ; return false; }  
  2. …  
  3. try 
  4. { … } 
  5. catch (Exception e) when (Log(e)) {}  
So, these are the things you should know while playing with exception filtering. I hope you enjoyed the post. See you later, Alligator!


Similar Articles