2014-01-09 147 views
-1

我正在處理一個android項目,我想弄清楚如何拋出異常回調用線程。拋出異常回到調用方法

我所擁有的是一項活動,當用戶點擊一個按鈕時,它會調用另一個Java類(不是活動,標準類)中的線程函數。標準類中的方法可以拋出IOExceptionException。我需要將異常對象拋回到活動中的調用方法,以便活動可以根據異常返回的內容做一些事情。

下面是我的活動代碼:

private void myActivityMethod() 
{ 
    try 
    { 
     MyStandardClass myClass = new MyStandardClass(); 
     myClass.standardClassFunction(); 
    } 
    catch (Exception ex) 
    { 
     Log.v(TAG, ex.toString()); 
     //Do some other stuff with the exception 
    } 
} 

下面是我的標準類函數

private void standardClassFunction() 
{ 
    try 
    { 
     String temp = null; 
     Log.v(TAG, temp.toString()); //This will throw the exception as its null 
    } 
    catch (Exception ex) 
    { 
     throw ex; //Don't handle the exception, throw the exception backto the calling method 
    } 
} 

當我把throw ex在異常時,Eclipse似乎是不開心,反而問我包圍在另一個try/catch中,throw ex,這意味着,如果我這樣做,則異常將在第二次嘗試/ catch中處理,而不是調用方法異常處理程序。

感謝您提供的任何幫助。

+0

'Exception'是一個檢查的異常。 'NullPointerException'也是一個'Exception',但它更具體地說是一個未被選中的'RuntimeException'。 –

+2

非常標準的java東西...只需將引發添加到您的方法聲明。 – Submersed

+0

http://docs.oracle.com/javase/tutorial/essential/exceptions/catchOrDeclare.html –

回答

2

變化:

private void standardClassFunction() 
{ 
    try 
    { 
     String temp = null; 
     Log.v(TAG, temp.toString()); //This will throw the exception as its null 
    } 
    catch (Exception ex) 
    { 
     throw ex; //Don't handle the exception, throw the exception backto the calling method 
    } 
} 

private void standardClassFunction() throws Exception 
{ 

     String temp = null; 
     Log.v(TAG, temp.toString()); //This will throw the exception as its null 

} 

如果你想處理扔在調用函數裏面調用功能異常。你可以通過抓住它而不是像上面那樣扔它。

此外,如果它是一個檢查異常像NullPointerException你甚至不需要寫入拋出。

更多關於檢查和unchecked異常:

http://www.geeksforgeeks.org/checked-vs-unchecked-exceptions-in-java/

+1

在這種情況下,'throws'是不必要的。 –

+0

是的。但是如果他的方法裏面有一些未經檢查的例外,他需要這樣做。我舉了一個例子 –

+0

在這種情況下,請添加一個省略號或解釋該註釋的註釋。 –

1
上述

,當你聲明拋出的方法簽名,編譯器知道,這種方法可能會拋出異常。

所以現在當你從另一個班級調用該方法時,你會被要求嘗試/趕上你的呼叫。

相關問題