System.Exception总是一个糟糕的做法? [英] Is it always a bad practice to catch System.Exception?

查看:132
本文介绍了System.Exception总是一个糟糕的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码段,它引发三个不同的异常(即 System.Configuration.ConfigurationErrorsException System.FormatException System.OverflowException ):

Please consider the following piece of code, which throws three different exceptions (namely, System.Configuration.ConfigurationErrorsException, System.FormatException and System.OverflowException):

int SomeInt = Convert.ToInt32(ConfigurationManager.AppSettings["SomeIntValue"]);

异常是不同的,所以在实践中我应该有三个不同的 catch 块来处理每个特定的异常。然而,在这种特殊情况下,所有异常都以相同的方式处理:日志被写入到EventViewer中,并且显示一条消息通知配置错误...在这个特殊原因中,使用

The exceptions are different, and so in practice I should have three different catch blocks to handle each particular exception. However, in this particular case, all exceptions are handled the same way: a log is written to, say, EventViewer, and a message informing of a configuration error is displayed... In this particular cause, is it too bad to use

try
{
    int SomeInt = ConfigurationManager.AppSettings["SomeIntValue"];
}
catch (Exception ThisException)
{
    /* Log and display error message. */
}

或者我应该使用三个 catch 阻止并重复每个代码中的代码?

or should I, instead, use the three catch blocks and repeat the code within each of them?

推荐答案

我不认为这是坏习惯如果你想要的功能是每当这个代码抛出一个异常,然后采取这些行动,那么我认为捕获System.Exception是完全适当的。

I don't think it's bad practice. If your desired functionality is "whenever this code throws an exception, then take these actions" then I think catching System.Exception is perfectly appropriate.

包装一个非常具体的框架功能,而不是大块的自定义代码,在我看来也有帮助。

The fact that you're wrapping a very specific framework function instead of a large block of custom code helps in my opinion as well.

这篇关于System.Exception总是一个糟糕的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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