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.
in C# 6 the recommended approach is to use Exception Filters, here is an example:
Cautioned and Warned: Yet another kind, functional style.
What is in the link doesn't answer your question directly, but it's trivial to extend it to look like:
(Basically provide another empty
Catch
overload which returns itself)The bigger question to this is why. I do not think the cost outweighs the gain here :)
Exception filters are now available in c# 6+. You can do
The accepted answer seems acceptable, except that CodeAnalysis/FxCop will complain about the fact that it's catching a general exception type.
Also, it seems the "is" operator might degrade performance slightly.
CA1800: Do not cast unnecessarily says to "consider testing the result of the 'as' operator instead", but if you do that, you'll be writing more code than if you catch each exception separately.
Anyhow, here's what I would do:
Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.
For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:
I highly recommend folks review this MSDN document:
Exception Hierarchy
Not in C# unfortunately, as you'd need an exception filter to do it and C# doesn't expose that feature of MSIL. VB.NET does have this capability though, e.g.
What you could do is use an anonymous function to encapsulate your on-error code, and then call it in those specific catch blocks: