【问题标题】:RMI and exceptionsRMI 和异常
【发布时间】:2010-10-11 09:11:00
【问题描述】:

我对使用 RMI 不熟悉,对使用异常也比较陌生。

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

我有一个为学生提供服务的简单服务器,并且我有 delete 方法,如果学生不存在,我想抛出一个自定义异常 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 是个坏主意。

【问题讨论】:

    标签: java networking rmi


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      是的,可以通过 RMI 引发异常。

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

      如需更详细的解释,look at another of my answers。简而言之,在使用 RMI 时要小心链接异常。

      【讨论】:

      • 呵呵,这个问题似曾相识!
      • 我实际上在发帖之前看过这个。为建议喝彩 - 我想我现在已经解决了问题
      【解决方案3】:

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

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

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

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

      【讨论】:

      • 编译器要求先捕获最具体的异常;你的例子不会编译。否则,好帖子。
      【解决方案4】:

      您的例外无需扩展RemoteException

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-04-04
        • 1970-01-01
        • 2012-10-13
        • 2012-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多