More Elegant Exception Handling Than Multiple Catc

2019-01-07 09:11发布

This question already has an answer here:

Using C#, is there a better way to handle multiple types of exceptions rather than a bunch of ugly catch blocks?

What is considered best practice for this type of situation?

For example:

try
{
    // Many types of exceptions can be thrown
}
catch (CustomException ce)
{
    ...
}
catch (AnotherCustomException ace)
{
    ...
}
catch (Exception ex)
{
    ...
}

8条回答
beautiful°
2楼-- · 2019-01-07 10:02

About the only other thing you can do is emulate VB.NET's exception filters:

try {
    DoSomething();
} catch (Exception e) {
    if (!ex is CustomException && !ex is AnotherCustomException) {
       throw;
    }
    // handle
}

Sometimes this is better, sometimes not. I'd mainly use it if there was some common logic I wanted in the handler, but the exceptions don't share a base type.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-07 10:05

Unfortunately, C# does not have user exception filters like VB.NET, so you're limited to:

  1. Catching a common ancestor to all exceptions. This may or may not be what you want, because there may be other descendant exception types that you do not want to catch.
  2. Moving the exception handling logic into another method and calling that from each handler.
  3. Repeating the exception logic for each handler.
  4. Moving the exception handling logic into a language that supports filters, such as VB.NET.
查看更多
登录 后发表回答