我刚开始使用RMI,并且对异常的使用也比较新。
我想要在RMI上抛出一个异常(这个可能吗?)
我有一个简单的服务器,提供学生信息,我有一个删除方法,如果学生不存在,我想抛出一个自定义的异常StudentNotFoundException,它扩展了RemoteException(这样做好吗?)
任何建议或指导将不胜感激。
服务器接口方法
/**
* 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());
}
}
学生未找到异常
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是一个不好的想法。