Page 182 - CSharp/C#
P. 182

the debugging experience much easier. Instead of stopping on the throw statement, the debugger
        will stop on the statement throwing the exception, with the current state and all local variables
        preserved. Crash dumps are affected in a similar way.


              Exception filters have been supported by the CLR since the beginning and they've
              been accessible from VB.NET and F# for over a decade by exposing a part of the
              CLR's exception handling model. Only after the release of C# 6.0 has the functionality
              also been available for C# developers.




        Using exception filters


        Exception filters are utilized by appending a when clause to the catch expression. It is possible to
        use any expression returning a bool in a when clause (except await). The declared Exception
        variable ex is accessible from within the when clause:


         var SqlErrorToIgnore = 123;
         try
         {
             DoSQLOperations();
         }
         catch (SqlException ex) when (ex.Number != SqlErrorToIgnore)
         {
             throw new Exception("An error occurred accessing the database", ex);
         }


        Multiple catch blocks with when clauses may be combined. The first when clause returning true will
        cause the exception to be caught. Its catch block will be entered, while the other catch clauses will
        be ignored (their when clauses won't be evaluated). For example:


         try
         { ... }
         catch (Exception ex) when (someCondition) //If someCondition evaluates to true,
                                                   //the rest of the catches are ignored.
         { ... }
         catch (NotImplementedException ex) when (someMethod()) //someMethod() will only run if
                                                                //someCondition evaluates to false
         { ... }
         catch(Exception ex) // If both when clauses evaluate to false
         { ... }




        Risky when clause


              Caution


              It can be risky to use exception filters: when an Exception is thrown from within the when
              clause, the Exception from the when clause is ignored and is treated as false. This
              approach allows developers to write when clause without taking care of invalid cases.

        The following example illustrates such a scenario:



        https://riptutorial.com/                                                                             128
   177   178   179   180   181   182   183   184   185   186   187