Page 183 - CSharp/C#
P. 183

public static void Main()
         {
             int a = 7;
             int b = 0;
             try
             {
                 DoSomethingThatMightFail();
             }
             catch (Exception ex) when (a / b == 0)
             {
                 // This block is never reached because a / b throws an ignored
                 // DivideByZeroException which is treated as false.
             }
             catch (Exception ex)
             {
                 // This block is reached since the DivideByZeroException in the
                 // previous when clause is ignored.
             }
         }

         public static void DoSomethingThatMightFail()
         {
             // This will always throw an ArgumentNullException.
             Type.GetType(null);
         }


        View Demo


        Note that exception filters avoid the confusing line number problems associated with using throw
        when failing code is within the same function. For example in this case the line number is reported
        as 6 instead of 3:


         1. int a = 0, b = 0;
         2. try {
         3.     int c = a / b;
         4. }
         5. catch (DivideByZeroException) {
         6.     throw;
         7. }


        The exception line number is reported as 6 because the error was caught and re-thrown with the
        throw statement on line 6.

        The same does not happen with exception filters:


         1. int a = 0, b = 0;
         2. try {
         3.     int c = a / b;
         4. }
         5. catch (DivideByZeroException) when (a != 0) {
         6.     throw;
         7. }


        In this example a is 0 then catch clause is ignored but 3 is reported as line number. This is
        because they do not unwind the stack. More specifically, the exception is not caught on line 5
        because a in fact does equal 0 and thus there is no opportunity for the exception to be re-thrown


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