尝试使用空的捕获 [英] Try with empty Catches

查看:21
本文介绍了尝试使用空的捕获的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个带有空 catch 的 try 语句,这是不好的做法吗?例如,说我有 2 次单独的尝试,其中一个可能失败但另一个成功或两者都成功或任何可能的组合.处理这样的代码是不好的做法吗?

Say I have a try statement with and empty catch is that bad practice? For example say I have 2 try separate trys where it is possible for one to fail but the other to succeed or both succeed or any possible combination of such. Is that bad practice to handle code like that?

示例

if( mode == Modes.EDIT ){
  try {user = userBo.findById(id).get(0); }
  catch(Exception e) { }
  try{
    result = this.initializeEntityById(accountDao, id);
    if( !result.equals(SUCCESS) ){
      return result;
    }   
  }
  catch(Exception e){ }
}

在这个例子中,关注的变量是id",我不确定传入的值是否有效,在前端这并不重要,因为代码处理传入的任何内容并提供正确的显示.

In this example the variable in concern is 'id' where I'm not sure if the value coming in is valid and on the front end it doesn't really matter because the code handles whatever comes in and provides correct display.

所以问题是:

  1. 对于空渔获物,这是一种不好的做法吗?
  2. 是否存在我没​​有意识到的潜在不稳定因素?
  3. 是否有更好的方法来实现我的目标?

推荐答案

  1. 是的,这总是不好的做法,因为您不知道哪里出了问题.您至少应该记录异常.
  2. 不稳定之处在于,当出现问题时,您不知道自己的代码出了什么问题.
  3. 在控制流中使用异常是不可取的.性能很差,异常应该只用于特殊情况.您可以执行以下操作:
  1. Yes it's always bad practice since you have no idea what went wrong where. You should at least log the exception.
  2. The instability is that when something goes wrong, you have no idea what is wrong with your code.
  3. It's never desirable to use exceptions for control-flow. The performance is atrocious, and exceptions should only be used for exceptional circumstances. Here's what you can do:
  1. 将异常作为方法签名的一部分,并让更高级别处理它.
  2. 捕获异常,但将其包装在符合语义的异常中并重新抛出,以便更高级别可以处理它.
  3. 处理它.这也可以通过多种方式完成:
  1. Make the exception part of the method signature and let a higher level handle it.
  2. Catch the exception, but wrap it in a semantically-appropriate exception and rethrow it so a higher level can handle it.
  3. Handle it. This can also be done in multiple ways:
  1. 不要让异常发生:不是捕获异常,而是对数据执行检查以查看它是否会导致异常.例如,在你的情况下,我认为你应该有一个像 userBo.existsWithId(id) 这样的方法,它会返回一个 boolean 表示用户是否存在.或者如果找不到用户,让 findById 返回 null,并检查是否 user == null.我认为这是您最好的选择.
  2. 以某种理智的方式从异常中恢复(取决于您的业务逻辑).
  1. Don't let the exception happen: instead of catching the exception, perform an inspection on the data to see if it can cause an exception. For example, in your case I think you should have a method like userBo.existsWithId(id) which will return a boolean that says whether the user exists. Or have the findById return null if the user cannot be found, and check to see if user == null. I think this is your best bet.
  2. Recover from the exception in some sane way (depends on your business logic).

这篇关于尝试使用空的捕获的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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