Exception filters in C# or Asp.net C# with C# 6

Exception filters in C# or Asp.net C# with C# 6:


Exception filters give developers the ability to add a condition (in the form of a boolean expression) to a catch block, allowing the catch to execute only if the condition evaluates to true.
On the other hand using an if statement inside a catch block and re-throwing the exception would stop the propagation of debug information in the original exception.
With exception filters, the exception continues to propagate upwards in the call stack
 unless the condition is met. Exception filters make the debugging experience much easier. Instead of stopping on the throwstatement, 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.



Using exception filters

It is possible to use any expression returning a bool type in a condition (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 (and their when clauses won't even 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())
 //some Method() will only run, if
                                                    
 //some Condition evaluates to false
{ ... }
catch(Exception ex)
 // If both when clauses evaluates to false
{ ... }

Comments