18

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

4

4 回答 4

12

可以抛出任何类型的异常(甚至是自定义异常),只要确保将它们打包到您的导出 .jar 文件中(如果您使用的是需要手动执行此操作的 Java 版本)。

不过,我不会继承 RemoteException。如果存在某种连接问题,通常会抛出这些问题。据推测,您的客户端处理连接问题的方式与其他类型的问题不同。当您捕获 RemoteException 或连接到不同的服务器时,您可能会告诉用户服务器已关闭。对于 StudentNotFoundException,您可能希望给用户另一个机会来输入学生信息。

于 2009-03-04T21:35:26.037 回答
6

是的,可以通过 RMI 抛出异常。

RemoteException不,扩展以报告应用程序故障不是一个好主意。RemoteException表示远程机制中的故障,例如网络故障。使用适当的例外,java.lang.Exception必要时扩展自己。

有关更详细的解释,请查看我的另一个答案。简而言之,在使用 RMI 时要小心链接异常。

于 2009-03-04T21:36:58.200 回答
3

我希望能够在 RMI 上引发异常(这可能吗?)

是的。任何东西都可以被序列化,即使是例外。我认为异常本身实现了可序列化。

我有一个为学生提供服务的简单服务器,并且我有删除方法,如果学生不存在,我想抛出一个自定义异常 StudentNotFoundException 扩展 RemoteException(这是一件好事吗?)

我会让它亲自扩展异常。您的例外就是您的例外,RemoteExceptions 是针对因连接原因而导致 RMI 出错的事情。

于 2009-03-04T21:37:53.550 回答
2

您的异常无需扩展RemoteException.

(值得注意的是,抛出的具体异常类型需要在服务器和客户端都使用的代码库中。)

于 2009-03-04T21:36:04.473 回答