Catch multiple exceptions at once?
.net, c#, exception
Solution
Catch `System.Exception` and switch on the types
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
}
else
throw;
}
Problem
It is discouraged to simply catch `System.Exception`. Instead, only the "known" exceptions should be caught. Now, this sometimes leads to unnecessary 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 fails expectedly, you want to "reset" the `object`. However, if there is an unexpected exception, I still want to throw that higher.
Related problems
- More Elegant Exception Handling Than Multiple Catch Blocks?
- What's the point of passing ExceptionDispatchInfo around instead of just the Exception?
- Throwing an AggregateException in my own code
- C# exception filter?
- What benefit does the new "Exception filter" feature provide?
- How to rethrow InnerException without losing stack trace in C#?
- Which is faster between is and typeof