Catch multiple exceptions at once?

前端 未结 27 2288
夕颜
夕颜 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:28

    Exception filters are now available in c# 6+. You can do

    try
    {
           WebId = new Guid(queryString["web"]);
    }
    catch (Exception ex) when(ex is FormatException || ex is OverflowException)
    {
         WebId = Guid.Empty;
    }
    

    In C# 7.0+, you can combine this with pattern matching too

    try
    {
       await Task.WaitAll(tasks);
    }
    catch (Exception ex) when( ex is AggregateException ae &&
                               ae.InnerExceptions.Count > tasks.Count/2)
    {
       //More than half of the tasks failed maybe..? 
    }
    

提交回复
热议问题