Catch multiple exceptions at once?

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

    in C# 6 the recommended approach is to use Exception Filters, here is an example:

     try
     {
          throw new OverflowException();
     }
     catch(Exception e ) when ((e is DivideByZeroException) || (e is OverflowException))
     {
           // this will execute iff e is DividedByZeroEx or OverflowEx
           Console.WriteLine("E");
     }
    
    0 讨论(0)
  • 2020-11-22 12:27

    In c# 6.0,Exception Filters is improvements for exception handling

    try
    {
        DoSomeHttpRequest();
    }
    catch (System.Web.HttpException e)
    {
        switch (e.GetHttpCode())
        {
            case 400:
                WriteLine("Bad Request");
            case 500:
                WriteLine("Internal Server Error");
            default:
                WriteLine("Generic Error");
        }
    }
    
    0 讨论(0)
  • 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..? 
    }
    
    0 讨论(0)
提交回复
热议问题