Exception Filtering in C# 6.0

Since its inception C# has been able to filter exceptions depending on the type of the exception. For example, while trying to access a resource from the file system, there are possibilities of different types of errors popping up like timeout, invalid handle, invalid operation etc. To handle these kind of scenarios we could simply have different catch block for each exception type like the sample given below

try
{
    using (StreamReader reader = new StreamReader("invalid-file.txt"))
    {
        reader.ReadToEnd();
    }
}
catch(FileNotFoundException e)
{
}
catch(IOException e)
{

}
catch(Exception e)
{
    //all other exceptions
}

 

But sometimes we may want the catch block to execute if and only if an additional condition is also met. So normally we will put in a conditional check inside catch block as shown below.

In C# 6.0 instead of putting the conditional logic inside the catch block we can make use of the exception filters to execute the catch block when the condition is met during an exception. We can use the when keyword to specify the condition along with the catch statement. Even though the code may look similar to the one in the earlier example, the main difference is that in the later example stack unwinding won't happen.

ie When we enter a catch block, all the stack frames for the for the methods below the current methods are dropped and we won't get any information about the exceution state in those frames thereby making it difficult to identify the root cause


No Comments

Add a Comment