It is discouraged to simply catch System.Exception
. Instead, only the "known" exceptions should be caught.
Now, this sometimes leads to unnecce
This is a classic problem every C# developer faces eventually.
Let me break your question into 2 questions. The first,
Can I catch multiple exceptions at once?
In short, no.
Which leads to the next question,
How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?
Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:
So the code looks like:
try
{
WebId = Guid.Empty;
Guid newGuid = new Guid(queryString["web"]);
// More initialization code goes here like
// newGuid.x = y;
WebId = newGuid;
}
catch (FormatException) {}
catch (OverflowException) {}
If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.
If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:
try
{
WebId = new Guid(queryString["web"]);
// More initialization code goes here.
}
catch (FormatException) {
Reset(WebId);
}
catch (OverflowException) {
Reset(WebId);
}