捕获空指针异常是一种代码味道吗? [英] Is Catching a Null Pointer Exception a Code Smell?

查看:19
本文介绍了捕获空指针异常是一种代码味道吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我的一个同事写了一些代码来捕获整个方法周围的空指针异常,并返回一个结果.我指出空指针可能有多种原因,因此我们将其更改为针对一个结果的防御性检查.

Recently a co-worker of mine wrote in some code to catch a null pointer exception around an entire method, and return a single result. I pointed out how there could've been any number of reasons for the null pointer, so we changed it to a defensive check for the one result.

然而,捕捉 NullPointerException 对我来说似乎是错误的.在我看来,空指针异常是错误代码的结果,而不是系统中预期的异常.

However, catching NullPointerException just seemed wrong to me. In my mind, Null pointer exceptions are the result of bad code and not to be an expected exception in the system.

在任何情况下捕获空指针异常是否有意义?

Are there any cases where it makes sense to catch a null pointer exception?

推荐答案

是的,捕获任何 RuntimeException 几乎总是一种代码异味.C2 Wiki 似乎同意.

Yes, catching any RuntimeException is almost always a code smell. The C2 Wiki seems to agree.

一个例外可能是一些特别防御性的代码片段,它们运行来自其他模块的几乎随机代码.此类防御结构的示例包括 EDT、ThreadPools/Executors 和插件系统.

An exception would probably be some specially defensive pieces of code which run pretty much random code from other modules. Examples for such defensive structures would be the EDT, ThreadPools/Executors and plugin system.

这篇关于捕获空指针异常是一种代码味道吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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