问题描述
哇,我刚回来,从外包开发C#一个庞大的工程,并要通过我的code检讨,而我的分析工具,揭示了它认为不好的东西串。其中一个更令人沮丧的消息是:
Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was:
Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects
开发人员向我保证他们有充分的理由为所有空catch块,有时与空catch块的尝试只是有忽略无用的异常和崩溃保持应用程序。我觉得这是一个警察并完成学士学位。有些其实我抬头一看是那里的记录被保存到数据库的数据库调用,在这种情况下,如果有异常被忽略,用户还是会回到一个不错的提示,觉得一切都还行,并继续与实例他们的工作。在现实中,他们的工作永远不会保存。我认为这绝对是最可怕的一种错误。在这种情况下,他们在扔了code在尝试用一个空的catch块完全错误的。但我的问题是,这是在任何情况下EVER接受吗?我想不会,但我已经知道是错误的。
The developers assure me they had good reason for all the empty catch blocks, that sometimes the try with empty catch blocks are just there to ignore useless exceptions and keep the application from crashing. I feel this is a cop out and complete BS. Some of the examples I actually looked up were database calls where the record was being saved to the database, and in this case, if an exception was ignored, the user would get back an okay prompt, think everything was okay, and continue on with their work. In reality, their work was never saved. I think this is absolutely the most horrible kind of error. In this case, they are completely wrong in throwing that code in a try with an empty catch block. But my question is, "Is this EVER acceptable in ANY situation?" I think not, but I've been known to be wrong.
推荐答案
虽然有忽视一些例外的理由合理;然而,一般只有你能够放心地忽略特定的异常。由于注意到Konrad鲁道夫的,你可能有赶上并吞下一个错误作为框架的一部分;并通过osp70,有可能是由你知道你可以忽略框架生成异常。
While there are some reasonable reasons for ignoring exceptions; however, generally it is only specific exceptions that you are able to safely ignore. As noted by Konrad Rudolph, you might have to catch and swallow an error as part of a framework; and as noted by osp70, there might be an exception generated by a framework that you know you can ignore.
在这两种情况下,虽然,你可能会知道这个异常类型,如果你知道类型,那么你应该有类似下面的code:
In both of these cases though, you will likely know the exception type and if you know the type then you should have code similar to the following:
try {
// Do something that might generate an exception
} catch (System.InvalidCastException ex) {
// This exception is safe to ignore due to...
} catch (System.Exception ex) {
// Exception handling
}
在您的应用程序的情况下,像类似可能适用于某些情况下,一些声音;但你给数据库的例子保存返回一个OK,即使有一个例外是不是一个非常好的迹象。
In the case of your application, is sounds like something similar might apply in some cases; but the example you give of a database save returning an "OK" even when there is an exception is not a very good sign.
这篇关于没有任何正当理由以往任何时候都忽略捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!