Improvement on Exception Handling in C# 6.0

In C# 6.0 two new features were introduced related to Exception Handling.
 
1. Now we can use await in a Catch and Finally block.
  1. try{  
  2.  do something  
  3. }  
  4. Catch {  
  5.  await Reset();  
  6. }  
  7. Finally{  
  8.  await Reset ();  
  9. }  
2. We can use an Exception Filter. For example: 
  1. using Microsoft.VisualStudio.TestTools.UnitTesting;  
  2. using System.ComponentModel;  
  3. using System.Runtime.InteropServices;  
  4.   
  5.  [TestMethod][ExpectedException(typeof(Win32Exception))]  
  6. public void ExceptionFilter_DontCatchAsNativeErrorCodeIsNot42()  
  7. {  
  8.   try  
  9.   {  
  10.     throw new Win32Exception(Marshal.GetLastWin32Error());  
  11.   }  
  12.   catch (Win32Exception exception)   
  13.     if (exception.NativeErrorCode == 0x00042)  
  14.   {  
  15.     // Only provided for elucidation (not required).  
  16.     Assert.Fail("No catch expected.");  
  17.   }  
  18. }  

The catch block now verifies that not only is the exception of type Win32Exception (or derives from it), but also verifies additional conditions; the specific value of the error code in this example.

There was no equivalent alternate way of coding exception filters prior to C# 6.0. Until now, the only approach was to catch all exceptions of a specific type, explicitly check the exception context and then re-throw the exception if the current state wasn't a valid exception-catching scenario.

Up Next
    Ebook Download
    View all
    Learn
    View all