Tuesday, 16 May 2017

c# - Catch multiple exceptions at once?



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.



Answer



Catch System.Exception and switch on the types



catch (Exception ex)            
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}


throw;
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...