是否有任何正当理由忽略捕获的异常 [英] Is there any valid reason to ever ignore a caught exception

查看:27
本文介绍了是否有任何正当理由忽略捕获的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哇,我刚刚从外包开发人员那里拿回了一个 C# 的大项目,在进行代码审查时,我的分析工具揭示了一堆它认为不好的东西.更令人沮丧的消息之一是:

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 块的 try 只是为了忽略无用的异常并防止应用程序崩溃.我觉得这是一个警察和完整的 BS.我实际查找的一些示例是将记录保存到数据库的数据库调用,在这种情况下,如果忽略异常,用户会得到一个好的提示,认为一切正常,然后继续他们的工作.实际上,他们的工作从未被保存.我认为这绝对是最可怕的错误.在这种情况下,他们在带有空 catch 块的 try 中抛出该代码是完全错误的.但我的问题是,这在任何情况下都可以接受吗?"我想不是,但我已经知道我是错的.

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.

推荐答案

虽然忽略异常有一些合理的理由;但是,通常只有特定的异常才能安全地忽略.正如康拉德·鲁道夫所述>,作为框架的一部分,您可能必须捕获并吞下错误;正如 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.

不过,在这两种情况下,您可能都知道异常类型,如果您知道类型,那么您的代码应该类似于以下内容:

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.

这篇关于是否有任何正当理由忽略捕获的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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