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

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

问题描述

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

什么是最好的做法对于这种类型的情况?

例如:

 尝试
{
    //很多类型的异常可以被抛出
}
赶上(CustomException CE)
{
    ...
}
赶上(AnotherCustomException ACE)
{
    ...
}
赶上(例外前)
{
    ...
}
 

解决方案

在我看来,一帮丑陋catch块是处理这种情况的最好办法。

我preFER这样做的原因是,这是很明确的。您明确指出要处理哪些异常,以及应如何处理。其他形式的尝试合并处理成更简洁的形式失去了大多数情况下的可读性。

我的建议是坚持这一点,并处理你想明确地处理,各自在自己的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?

For example:

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

解决方案

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.

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天全站免登陆