Follow @endyourif rss Facebook LinkedIn

Catching multiple exceptions with C# Catching multiple exceptions with C#

Published on Jan 26, 2020

Try/catch blocks are a part of my everyday life. But I'm not a fan of catching all exceptions. I prefer handling only the ones I expect to be thrown in specific situations. Of course I can accomplish this with multiple catch blocks, but when they all do common things I would like a simpler way to avoid code duplication.



Example with multiple catch blocks:


try
{
    var doSomething = new FormatException();
}
catch (FormatException ex)
{
    Log.Error(string.Format("FormatException occurred: {0}", ex.Message));
}
catch (OverflowException ex)
{
    Log.Error(string.Format("OverflowException occurred: {0}", ex.Message));
}


In this example the only difference is the start of the error logging string, but imagine you needed to return a common response object with a success boolean. In the above example there is some code duplication of Log.Error that I would like to avoid.

So in an example like this, I prefer to catch the generic Exception and handle the specific types; otherwise, throw the exception to be handled higher up in the code:


try
{
    var doSomething = new FormatException();
}
catch (Exception ex)
{
	if (ex is FormatException || ex is OverflowException) {
		Log.Error(string.Format("{0} occurred: {1}", ex.Type.Name, ex.Message));
		
		return;
	}
	
	throw;
}


The above code checks that the exception type is one of the exceptions we want to handle and performs the same logging we wanted to accomplish in the first example. If the exception is something else I'm using the throw so any other exception will bubble up the code base.

Tags: ASP.NET MVC and Web API Tutorial | c# | exception

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP