2013-08-22 21 views
1

我有下面的代碼,我喜歡用finally語句來獲取異常消息,通過使用catch語句我可以很容易地獲得它的arg.but儘可能多的我知道我無法獲得使用finally的異常消息。使用finally語句在java中捕獲異常並使用它的消息

try { 
MyClass obj=new MyClass(); 
obj.strProName = jobj1.getString("productname"); 
obj.strPrice = jobj1.getString("price"); 
obj.strCurrency = jobj1.getString("currency"); 
obj.strSalePrice = jobj1.getString("saleprice"); 
obj.strStoreName = jobj1.getString("storename"); 

//arrayList.add(obj); 
throw new Exception("Exception Reason!"); 

} 
finally{ 
//want to get that exception message here without using catch or can see how finally catching here the exception 
} 

回答

2

finally沒有發現異常。您只能在catch區塊中發現異常。 finally塊的目的是在兩種情況下執行,即它將執行而不管是否發生異常。

3

但是儘管我知道我不能在最終使用 獲得異常消息。

這是正確的,到的錯誤時拋出你,嗯...有使用條款。您可以將消息存儲在變量中(在catch子句中),然後在finally子句中使用該變量。

6

不像catch blockfinally塊一點兒也不接受任何exception例如

所以,答案是否定的,從我的身邊。

我的意思是打印信息,你需要Exception實例。

作爲每文檔(jls-14.2

A嵌段是語句,局部類聲明,並且括號內的局部變量聲明的語句序列。

因此,在catch catch塊catch(Exception e) {}之外,您無法訪問它(e)。

+1

@sureshatta你一條線是值得我3行:)給予好評,從我 –

+1

我知道這一點,但現在還我的問題仍然沒有答案。因爲我想知道只有這個東西如何通過finally.as解決新的異常(「消息」),他們必須是任何一個字符串參數方法需要被調用,但catch不存在,但捕獲是..你可以建議這件事 –

0

試試這個

try { 
     ..... 
     throw new Exception("Exception Reason!"); 
    } 
catch(Exception e){ 
    msg=e.getMessage(); 
finally{ 
//USE String msg here. 
} 
+1

我在我的問題中也提到了這個,但是我想用最後沒有抓到的信息來獲取信息,因爲現在你終於可以接受這一點了。 –

+0

是的。但是你不能用finally塊捕捉異常。我以爲你可能想在最後阻止消息這就是爲什麼我建議上述選項。 –

+0

我想知道Exception類的字符串arg構造函數是如何由拋出的異常來管理的,以防當我們沒有使用catch.i時只有這種混淆。你可以建議這個 –

1

最後沒有捕獲的異常,它只是你可以用它來經常做東西的事,就算是沒有錯誤,美中不足的是從來沒有要求。

try { 
MyClass obj=new MyClass(); 
obj.strProName = jobj1.getString("productname"); 
obj.strPrice = jobj1.getString("price"); 
obj.strCurrency = jobj1.getString("currency"); 
obj.strSalePrice = jobj1.getString("saleprice"); 
obj.strStoreName = jobj1.getString("storename"); 
} 
//arrayList.add(obj); here you can Catch the exception, meaning it will only show if there is an exception! 
catch(Exception e){ 
System.out.print(e+"=Exception Reason!"); 
} 
finally{ 
//Finally is used to do something no matter what. 
//It will do what ever you want it to do, 
//even if the catch is never used. 
//Use catch to show exception, 
//finally to close possible connections to db etc. 
} 
+1

這個答案在這裏沒有任何新的,因爲我也提到了我的問題也類似。我想知道如何使用finally來獲取消息,沒有catch,因爲它必須是任何Exception(String)cons將會被調用,但通過使用我們沒有在code.so中提供這些代碼,或者我們如何最終做到這一點。我只想知道這件事情。你可以把這個想法放在一些東西上 –

相關問題