Conditional Exception Handling – Exception Filters in C# 6.0

Conditional Exception Handling – Exception Filters in C# 6.0

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
{
}
DON'T MISS OUT!
Subscribe To Newsletter For your Daily Development Tips and Tricks  

 Best Tips & Tricks on Microsoft Technology Platform 

Invalid email address
We promise not to spam you. You can unsubscribe at any time.
Abhijit Jana

Abhijit runs the Daily .NET Tips. He started this site with a vision to have a single knowledge base of .NET tips and tricks and share post that can quickly help any developers . He is a Former Microsoft ASP.NET MVP, CodeProject MVP, Mentor, Speaker, Author, Technology Evangelist and presently working as a .NET Consultant. He blogs at http://abhijitjana.net , you can follow him @AbhijitJana . He is the author of book Kinect for Windows SDK Programming Guide.

One Comment to “Conditional Exception Handling – Exception Filters in C# 6.0”

Comments are closed.