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.
- try{
- do something
- }
- Catch {
- await Reset();
- }
- Finally{
- await Reset ();
- }
2. We can use an Exception Filter. For example:
- using Microsoft.VisualStudio.TestTools.UnitTesting;
- using System.ComponentModel;
- using System.Runtime.InteropServices;
-
- [TestMethod][ExpectedException(typeof(Win32Exception))]
- public void ExceptionFilter_DontCatchAsNativeErrorCodeIsNot42()
- {
- try
- {
- throw new Win32Exception(Marshal.GetLastWin32Error());
- }
- catch (Win32Exception exception)
- if (exception.NativeErrorCode == 0x00042)
- {
-
- Assert.Fail("No catch expected.");
- }
- }
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.