我是使用 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());
}
}
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 是个坏主意。