Exception Handling in C# 6.0

Tags: .Net, C#, C# 6.0, Exception Handling

In C# 6 the exception condition/ exception filters feature was added.

try 
{


    // work

}
catch (Exception ex) when ( /* filter expression */ ) 
{

    //handle exception

}

The general rule is:

Avoid System.Exception and general catch blocks except to gracefully log the exception before shutting down the application.

Summary of guidelines for catching exceptions:

  • Avoid catching exceptions that you’re unable to handle fully
  • Avoid hiding exceptions you don’t fully handle
  • Do use throw to re-throw an exception; rather than throw new <exception object> inside a catch block;
  • Consider an exception condition in favor of having to re-throw an exception after capturing one you can’t handle
  • Avoid throwing exceptions from exception conditional expression
  • Do use caution when re-throwing different exceptions
  • Rarely use System.Exception and general catch blocks – except to log the exception before shutting down the application
  • Avoid exception reporting or logging lower in the call stack


References:

No Comments

Add a Comment