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

有帮助吗?

解决方案

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

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

其他提示

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

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

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

  

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

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

  

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

我会亲自扩展Exception。您的例外是您的例外,而RemoteExceptions用于出于连接原因而出现RMI出错的情况。

您的例外无需扩展 RemoteException

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top