Filtering exceptions in C# 6

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.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: