Filtering exceptions in C# 6
February 24, 2016 Leave a comment
There’s a new keyword in C# 6 which can only be used in conjunction with exception handling: when. With when we can put a filter on our catch clauses: catch a certain type of exception, e.g. IOException, but only if a certain condition is true. Otherwise continue with the next catch-clause if any.
Consider the following example:
try { throw new IOException("missing"); } catch (IOException ioe) when (ioe.Message == "missing") { Console.WriteLine("The file is missing"); } catch (IOException ioe) when (ioe.Message == "cannot open") { Console.WriteLine("The file is read-only"); } catch (IOException ioe) { Console.WriteLine("Some other IO exception: {0}", ioe.Message); }
We deliberately throw an IOException with the message “missing”. Then we have 3 catch clauses, 2 with a when sub-clause. The first one says “catch an IOException if its message is equal to missing”. The second will catch IOExceptions with the message “cannot open”. Finally we have a generic catch clause for any other type of IOExceptions.
There can be any kind of boolean statement after the when keyword, you don’t have to refer back to the exception.
View all various C# language feature related posts here.