2012-02-29 77 views
6

我是C程序員,最近剛學習一些java,因爲我正在開發一個android應用程序。目前我處於一種狀況。以下是一個。如何在java中傳播異常

public Class ClassA{ 

public ClassA(); 

public void MyMethod(){ 

    try{ 
    //Some code here which can throw exceptions 
    } 
    catch(ExceptionType1 Excp1){ 
    //Here I want to show one alert Dialog box for the exception occured for the user. 
    //but I am not able to show dialog in this context. So I want to propagate it 
    //to the caller of this method. 
    } 
    catch(ExceptionType2 Excp2){ 
    //Here I want to show one alert Dialog box for the exception occured for the user. 
    //but I am not able to show dialog in this context. So I want to propagate it 
    //to the caller of this method. 
    } 
    } 
} 

現在我想在另一個類的其他地方調用方法MyMethod()。如果有人可以提供一些代碼片段,以便如何將異常傳播給MyMethod()的調用者,以便我可以在調用方法的對話框中顯示它們。

對不起如果我不是那麼清楚和怪異的問這個問題的方式。

+1

參見http://stackoverflow.com/questions/409563/best-prac tices換異常管理功能於Java的或-C-尖銳 – mglauche 2012-02-29 12:34:45

回答

20

只要不趕擺在首位之外,並改變你的方法聲明,以便它可以傳播他們:如果你需要採取一些行動,然後繁殖

public void myMethod() throws ExceptionType1, ExceptionType2 { 
    // Some code here which can throw exceptions 
} 

,你可以重新拋出:

public void myMethod() throws ExceptionType1, ExceptionType2 { 
    try { 
     // Some code here which can throw exceptions 
    } catch (ExceptionType1 e) { 
     log(e); 
     throw e; 
    } 
} 

這裏ExceptionType2根本沒有被抓到了 - 它只是自動傳播起來。 ExceptionType1被捕獲,記錄,然後重新排列。

不是一個好主意,有catch塊這只是重新拋出異常 - 除非有一些微妙的原因(例如,以防止更廣泛的catch塊從處理它),你通常應該只是刪除catch塊,而不是。

0

只是重新拋出異常

throw Excp1;

你需要將異常類型添加到MyMthod()聲明這樣

public void MyMethod() throws ExceptionType1, ExceptionType2 { 

    try{ 
    //Some code here which can throw exceptions 
    } 
    catch(ExceptionType1 Excp1){ 
     throw Excp1; 
    } 
    catch(ExceptionType2 Excp2){ 
     throw Excp2; 
    } 
} 

或者只是省略try可言,因爲你不再處理異常,除非在重新拋出異常之前在catch語句中執行一些額外的代碼。

2

不要抓住它再重新拋出。只要做到這一點,並抓住它的地方,你想

public void myMethod() throws ExceptionType1, ExceptionType2 { 
    // other code 
} 

public void someMethod() { 
    try { 
     myMethod(); 
    } catch (ExceptionType1 ex) { 
     // show your dialog 
    } catch (ExceptionType2 ex) { 
     // show your dialog 
    } 
} 
0

我總是做這樣的:

public void MyMethod() throws Exception 
{ 
    //code here 
    if(something is wrong) 
     throw new Exception("Something wrong"); 
} 

那麼當你調用函數

try{ 
    MyMethod(); 
    }catch(Exception e){ 
    System.out.println(e.getMessage()); 
}