Catch multiple exceptions at once?

前端 未结 27 2278
夕颜
夕颜 2020-11-22 11:31

It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.

Now, this sometimes leads to unnecce

27条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 12:07

    This is a variant of Matt's answer (I feel that this is a bit cleaner)...use a method:

    public void TryCatch(...)
    {
        try
        {
           // something
           return;
        }
        catch (FormatException) {}
        catch (OverflowException) {}
    
        WebId = Guid.Empty;
    }
    

    Any other exceptions will be thrown and the code WebId = Guid.Empty; won't be hit. If you don't want other exceptions to crash your program, just add this AFTER the other two catches:

    ...
    catch (Exception)
    {
         // something, if anything
         return; // only need this if you follow the example I gave and put it all in a method
    }
    

提交回复
热议问题