比多个 Catch 块更优雅的异常处理? [英] More Elegant Exception Handling Than Multiple Catch Blocks?

查看:25
本文介绍了比多个 Catch 块更优雅的异常处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 C#,有没有更好的方法来处理多种类型的异常而不是一堆丑陋的 catch 块?

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?

例如:

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

推荐答案

在我看来,一堆丑陋"的 catch 块是处理这种情况的最好方法.

In my opinion, a bunch of "ugly" catch blocks IS the best way to handle that situation.

我喜欢这个的原因是它非常明确.您明确说明要处理哪些异常,以及应如何处理它们.在大多数情况下,尝试将处理合并为更简洁的形式的其他形式会失去可读性.

The reason I prefer this is that it is very explicit. You are explicitly stating which exceptions you want to handle, and how they should be handled. Other forms of trying to merge handling into more concise forms lose readability in most cases.

我的建议是坚持这一点,并处理您希望明确处理的异常,每个异常都在自己的 catch 块中.

My advice would be to stick to this, and handle the exceptions you wish to handle explicitly, each in their own catch block.

这篇关于比多个 Catch 块更优雅的异常处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆