简体   繁体   English

异常处理反模式:为什么log和return null是反模式

[英]Exception Handling Anti-patterns: Why log and return null is an anti-pattern

An article on Exception handling anti-patterns mentions (Refer: https://today.java.net/article/2006/04/04/exception-handling-antipatterns ) that Log and Return Null is an anti-pattern. 一篇关于异常处理反模式的文章(参见: https//today.java.net/article/2006/04/04/exception-handling-antipatterns ),Log和Return Null是一种反模式。 The reason given is “Instead of returning null, throw the exception, and let the caller deal with it. 给出的原因是“不是返回null,抛出异常,让调用者处理它。 You should only return null in a normal (non-exceptional) use case” 您应该只在正常(非例外)用例中返回null“

According to the article, following code is a bad programming practice and anti-pattern 根据文章,下面的代码是一个糟糕的编程实践和反模式

catch (NoSuchMethodException e) {
  LOG.error("Blah", e);
  return null;
}

catch (NoSuchMethodException e) {
  e.printStackTrace();
  return null;
}

I request some more explanation. 我要求更多解释。 I can understand why just returning null is an anti-pattern as it swallows the exception losing the information forever. 我可以理解为什么只返回null是一个反模式,因为它吞下了永远丢失信息的异常。 But with LOG.error("Blah", e); 但是用LOG.error(“Blah”,e); and e.printStackTrace();, the information is logged or printed and is not lost – so why it is an anti-pattern? 和e.printStackTrace();,信息被记录或打印,不会丢失 - 那么为什么它是反模式?

The caller gets no additional semantic information about what error occurred, nor why it occurred. 调用者不会获得有关发生错误的其他语义信息,也不会发生错误。 Did they pass bad input? 他们传递了错误的输入吗? In that case, give them a client-focused error (which will translate better across RPC or some other kind of remote-invocation). 在这种情况下,给他们一个以客户为中心的错误(这将在RPC或其他类型的远程调用中更好地转换)。 Did some dependent upstream service go away? 一些依赖的上游服务是否消失了? Throw a semantic exception so that the caller can provide useful feedback to the user (eg, "The database is unavailable. Please call the help desk at..."). 抛出语义异常,以便调用者可以向用户提供有用的反馈(例如,“数据库不可用。请拨打帮助台......”)。 null makes it impossible to respond to errors in meaningful ways - it just becomes the catch-all "an error occurred". null使得无法以有意义的方式响应错误 - 它只是变成了“发生错误”的全部错误。

The article referenced conflates the use of exceptions and null usage. 引用的文章混淆了异常和null使用的使用。 In general swallowing an exception is an anti-pattern. 通常吞咽异常是一种反模式。 However, in some situations if the catch block is providing information or side-effects thru other means it is a valid approach. 但是,在某些情况下,如果catch块通过其他方式提供信息或副作用,则这是一种有效的方法。 For example, the code can create an exception handler to a visitor. 例如,代码可以为访问者创建异常处理程序。 Also, throwing an exception is meaningless if there is no one to catch it. 此外,如果没有人抓住它,抛出异常是没有意义的。 Are there scenarios where this is true? 是否存在这种情况?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM