我的 RMI 服务器接口(interface)声明了一个方法 foo(),该方法被声明为抛出 RemoteException 和 Exception,如下所示:
public interface Node extends RemoteService {
public void foo() throws RemoteException, Exception;
}
服务器实现是:
public class NodeImpl extends UnicastRemoteObject implements Node {
public void foo() throws RemoteException, Exception {
// Implementation - calls other stuff...
}
}
我的客户端在服务器上调用 foo:
try {
node.foo();
}
catch (Exception e) {
System.err.print("Got exception from foo() of type " + e.getClass().getName());
System.err.println("Exception: " + e.getMessage());
}
现在,当我运行客户端时,我得到:
Got exception from foo() of type java.rmi.UnexpectedException Exception: undeclared checked exception; nested exception is: java.io.InterruptedIOException: The operation timed out
Java doc 是这样描述 java.rmi.UnexpectedException 的:
An UnexpectedException is thrown if the client of a remote method call receives, as a result of the call, a checked exception that is not among the checked exception types declared in the throws clause of the method in the remote interface.
但是我的远程接口(interface)指定 foo() 抛出异常,而 java.io.InterruptedIOException 是一种异常。那么为什么我的客户端会收到 UnexpectedException?
谢谢, 汤姆
最佳答案
But my remote interface specifies that foo() throws Exception, and java.io.InterruptedIOException is a kind of Exception. So why does my client get UnexpectedException
因为
throws Exception
表示该方法可以抛出类类型 Exception
的异常或其任何子类类型。 InterruptedIOException
是 Exception
的子类所以该方法抛出 InterruptedIOException
是完全有效的当在签名中时其父类(super class)型 Exception
提到了。
关于java - 客户端收到未声明的已检查异常,但已声明异常被捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24318189/