Capturing Multiple Exceptions in a single Catch statement in C# 6

csharpFor some time now developers wanted to catch multiple exceptions in a single Catch statement in order to not repeat their code in multiple catch statements. This was not available in previous releases of C# and developers used different workarounds to achieve it.

Some developers would simply accept the fact that this is the way to go so they would write code that looked like the following

Now in the above code, three catch statements have the same internal code yet the way the language was created cannot allow you to combine them in one which led to repetition of code and unnecessary verbosity.

Many developers tried to tackle this using a workaround by writing the following code

This kind of solves the problem but still, it kind of looks ugly, and it is not really helpful to clutter your catch statements with if statements.

And this problem came to be resolved with C# 6. Multiple exceptions in one catch statement. The above code would be simplified to the following

This is a lot more helpful and easier to understand now. In specific exception cases handle them in a specific way, while in all others handle it differently.
This also helps a lot when you have let’s say handling three types of exceptions in one way, two others in another way, and then something completely different for all other exceptions.
Even though you should never over complicate your code with too much code that might throw exceptions coupled in together but still, it’s a nice new little feature of C#

In a following post I will go more in depth explaining the different uses of exception filters in C#

Leave a Reply