2009-03-04 58 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出於連接原因出錯的情況。