C# language feature:

  • Exception filters

applies to

  • Exception Handling

benefit

  • Allows specification of conditions along with a catch block. The catch block is only executed if the condition satisfies.

how to use

  • To handle exception with a “specific condition”, add expression which evaluates to true following when or if keywords.

note

  • A Fundamental difference when compared with traditional exception handling. If your condition is in the catch block, you are catching the exception and then checking the condition,while with Exception Filters you are checking the condition before catching the exception. If the condition is not satisfied, the catch block is skipped and the code moves to check if there are other catch blocks matching the exception.

note 2

  • Expressions such as a log function evaluating to false allows logging of all exceptions (and will fall through to more specific handling).

example:

        
        public void Exception_Filters_Example()
        {
            try {
                throw new Exception("this will fail!");
            }
            catch (Exception e) when (LogException(e))
            {
                // This is never reached as logexception always returns false!
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                // Exceptions processed here.
            }
        }
        public static bool LogException(Exception e)
        {
            Console.Error.WriteLine(@"Exceptions are always recorded: {e}");
            return false;  // returning false forces move to next exception in catch block
        }