Conditional Exception Handling – Exception Filters in C# 6.0

By | December 8, 2014

C# 6.0 has two changes for exception handling. In the previous post we have discussed about Using await in a catch or finally block – in C# 6.0 , and the another one is the filtering the exception. While Using await in a catch or finally block is a welcome change for developers, we can consider exception filter is anther feature that gives lots of flexibility to the developers to deal with exceptions. So what’s this exception filtering? This help us to filter the exception ( catches the exceptions) by providing conditional statements which returns true or false to the catch block.


Following code snippets shows a quick use the exception filtering.

try
{
// Some exception
}
catch (Exception e) if (e.InnerException != null)
{
// handle the exception
}
finally
{

}

As shown in the above code, a if statement added to the right of the exception block. This mean, code block will only execute if the specified condition is true. We can specify multiple level of catch block with different condition. As per the execution flow, it will be one by one with fallback approch.

try
{
// Some exception
}
catch (InvalidOperationException ioe) if (Condition1)
{
// handle the exception
}
catch (FieldAccessException fae) if (Condition2)
{
// handle the exception
}
catch(Exception exp)
{

}
finally
{
}

One thought on “Conditional Exception Handling – Exception Filters in C# 6.0

  1. Pingback: Download PPT – “A lap around C# 6.0 and Visual Studio 2015 Preview” – MUGH Dev Day– 29th Nov 2014 | Abhijit's World of .NET

Comments are closed.