It is discouraged to simply catch System.Exception
. Instead, only the "known" exceptions should be caught.
Now, this sometimes leads to unneccessary repetitive code, for example:
try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty
call once?
The given example is rather simple, as it's only a GUID
. But imagine code where you modify an object multiple times, and if one of the manipulations fail in an expected way, you want to "reset" the object
. However, if there is an unexpected exception, I still want to throw that higher.
This is a variant of Matt's answer (I feel that this is a bit cleaner)...use a method:
Any other exceptions will be thrown and the code
WebId = Guid.Empty;
won't be hit. If you don't want other exceptions to crash your program, just add this AFTER the other two catches:Catch
System.Exception
and switch on the typesWith C# 7 the answer from Michael Stum can be improved while keeping the readability of a switch statement:
How about
Update 2015-12-15: See https://stackoverflow.com/a/22864936/1718702 for C#6. It's a cleaner and now standard in the language.
Geared for people that want a more elegant solution to catch once and filter exceptions, I use an extension method as demonstrated below.
I already had this extension in my library, originally written for other purposes, but it worked just perfectly for
type
checking on exceptions. Plus, imho, it looks cleaner than a bunch of||
statements. Also, unlike the accepted answer, I prefer explicit exception handling soex is ...
had undesireable behaviour as derrived classes are assignable to there parent types).Usage
IsAnyOf.cs Extension (See Full Error Handling Example for Dependancies)
Full Error Handling Example (Copy-Paste to new Console app)
Two Sample NUnit Unit Tests
Matching behaviour for
Exception
types is exact (ie. A child IS NOT a match for any of its parent types).Just call the try and catch twice.
It is just that Simple!!