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.0,Exception Filters is improvements for exception handling
For the sake of completeness, since .NET 4.0 the code can rewritten as:
TryParse never throws exceptions and returns false if format is wrong, setting WebId to
Guid.Empty
.Since C# 7 you can avoid introducing a variable on a separate line:
You can also create methods for parsing returning tuples, which aren't available in .NET Framework yet as of version 4.6:
And use them like this:
Next useless update to this useless answer comes when deconstruction of out-parameters is implemented in C# 12. :)
If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:
Some people think this code is the same as
But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.
See a discussion about this on CodePlex. And an example showing the difference.