C# - Exception filters

Exception filters

Exception filters is introduced in C# from version 6.0. Exception filters allows us to determine a conditional clause for a catch block. If the condition specified in the Exception filter evaluates to true, then only the catch block will executes, other wise it will be skipped.

try
{
 // Some HTTP operation
}
catch (HttpException ex) when (ex.GetHttpCode() == 400)
{
 return "Page not found";
} 
catch (HttpException ex) when (ex.GetHttpCode() == 500)
{
 return "Internal server error occured";
} 

Here, the first catch block will executes only if the HttpException occurs with 400 status code.
Before exception filters (C#  version < 6.0) the code looks like the following

try
{
 // Some HTTP operation
}
catch (HttpException ex) 
{
 if(ex.GetHttpCode() == 400)
  return "Page not found";
 else if(ex.GetHttpCode() == 500)
  return "Internal server error occured";
 else
  throw;
} 

In the above case, if we got the error codes other than 400, 500 then the throw will execute and some information like stack trace, local variables information etc, between this throw and the actual exception will change or lost. But using the Exception filters, as the expression evaluates to false and no catch block will handles this, the actual information will persists.

Another use of this exception filters is we can prevent the catch block will execute when we debug the code. For example, in the below code, catch block will not execute in debug mode

try
{
 // Some HTTP operation
}
catch (HttpException ex) when (!System.Diagnostics.Debugger.IsAttached)
{
 // Only catch exceptions when a debugger is not attached.
 // Otherwise, this should stop in the debugger. 
 return "Page not found";
}

Check Microsoft here for more details 

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment