为什么 NullPointerException 是运行时异常,而 RemoteException 不是?
NullPointerException 是运行时异常的一个可能原因是每个方法都可以抛出它,因此每个方法都需要有一个“抛出 NullPointerException”,并且会很丑陋。但这会发生在 RemoteException 中。
由于 RemoteException 不是运行时异常,一个可能的原因是告诉客户端处理该异常。但远程环境中的每个方法都需要抛出它,因此与抛出 NullPointerException 没有区别。
猜测?我说清楚了吗?
A possible reason because a NullPointerException is a runtime exception is because every method can throw it, so every method would need to have a "throws NullPointerException", and would be ugly. But this happens with RemoteException.
And a possible reason because RemoteException is not a runtime exception, is to tell it client to treat the exception. But every method in a remote environment need throws it, so there is no difference of throwing NullPointerException.
Speculations? Was I clear?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不会讨论这个决定,我只是引用 Ann Wollrath(Java RMI 的设计和实现的领导者)对这个决定的解释。这是从 消息(1999 年 1 月的消息):
I won't discuss the decision, I'll just quote the explanation of the decision from Ann Wollrath (who lead the design and implementation of Java RMI). This is extracted from this message from the RMI-USERS archives (message from Jan 1999):
NullPointerException
比RemoteException
的潜力要大得多。任何调用对象方法的代码(实际上是指任何 Java 代码)都可能抛出NullPointerException
。只有 RMI 代码可以抛出RemoteException
。这是“所有代码”的一小部分。在编写 RMI 库时,设计者决定让客户端代码能够处理这些异常。考虑到远程代码执行的性质,我认为这是合理的。
There is vastly more potential for
NullPointerException
thanRemoteException
. Any code that calls a method on an object (meaning practically any Java code at all) could potentially throw aNullPointerException
. Only RMI code can throw aRemoteException
. This is a tiny subset of "all code."When writing the RMI libraries, the designers decided to make the client code expect to deal with these exceptions. Considering the nature of remote code execution, I think that's reasonable.
我的理解是:
例如,NullPointerException 始终可以避免,因此是未经检查的异常。当存在网络故障时,可能会发生 RemoteException,而在方法调用之前无法合理阻止该故障,因此需要进行检查。
The way I understand it is:
For example, NullPointerExceptions can always be avoided and are therefore unchecked exceptions. A RemoteException could occur when there is a network failure, which cannot be reasonably prevented before the method call and therefore is checked.
除了
RemoteException
仅适用于java.rmi
和javax.rmi
包(及其子包)中的代码之外,RemoteException
是一种IOException
类型,很像SocketException
是...并且所有IOException
都是检查异常。Besides
RemoteException
only applying to code fromjava.rmi
andjavax.rmi
packages (and their subpackages),RemoteException
is a type ofIOException
, much likeSocketException
is... and allIOException
s are checked exceptions.