我刚开始使用 RMI,而且我对使用异常比较陌生。
我希望能够通过 RMI 抛出异常(这可能吗?)
我有一个为学生提供服务的简单服务器,我有删除方法,如果学生不存在,我想抛出一个扩展 RemoteException 的自定义异常 StudentNotFoundException(这是一件好事吗?)
如有任何建议或指导,我们将不胜感激。
服务器接口(interface)方法
/**
* Delete a student on the server
*
* @param id of the student
* @throws RemoteException
* @throws StudentNotFoundException when a student is not found in the system
*/
void removeStudent(int id) throws RemoteException, StudentNotFoundException;
服务器方法实现
@Override
public void removeStudent(int id) throws RemoteException, StudentNotFoundException
{
Student student = studentList.remove(id);
if (student == null)
{
throw new StudentNotFoundException("Student with id:" + id + " not found in the system");
}
}
客户端方法
private void removeStudent(int id) throws RemoteException
{
try
{
server.removeStudent(id);
System.out.println("Removed student with id: " + id);
}
catch (StudentNotFoundException e)
{
System.out.println(e.getMessage());
}
}
StudentNotFoundException
package studentserver.common;
import java.rmi.RemoteException;
public class StudentNotFoundException extends RemoteException
{
private static final long serialVersionUID = 1L;
public StudentNotFoundException(String message)
{
super(message);
}
}
感谢您的回复,我现在已经设法解决了我的问题,并意识到扩展 RemoteException 是个坏主意。
最佳答案
可以抛出任何类型的异常(甚至是自定义异常),只需确保将它们打包到您的导出 .jar 文件中(如果您使用的是需要手动执行此操作的 Java 版本)。
不过,我不会继承 RemoteException。如果存在某种连接问题,通常会抛出这些错误。据推测,您的客户端处理连接问题的方式与其他类型的问题不同。当您捕获到 RemoteException 或连接到另一台服务器时,您可能会告诉用户服务器已关闭。对于 StudentNotFoundException,您可能希望给用户另一次输入学生信息的机会。
关于java - RMI 和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/612520/