2009-03-04 53 views
16

我是使用RMI的新手,我使用异常比较新。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是个坏主意。

回答

11

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

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

2

没有必要为您的例外延长RemoteException

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

5

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

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

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

+0

嘿,这个问题看起来很熟悉! – 2009-03-04 21:43:21

+0

我在发帖前实际上看过这个。欢呼的建议 - 我认为我现在已经解决了这个问题 – Malachi 2009-03-04 21:44:12

2

我希望能够通过RMI抛出一个异常(这可能吗?)

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

我有担任了学生一个简单的服务器,我有删除的,如果学生不存在,我想抛出StudentNotFoundException的自定义异常延伸RemoteException的方法(这是一个很好的事是什么?)

我会让它自己扩展Exception。您的异常是您的异常,并且RemoteExceptions适用于RMI出于连接原因出错的情况。