![](/img/trans.png)
[英]method that throws exception that calls another method that throws a different exception (java)
[英]Lambda return method which calls method that throws exception
我有以下問題。 我在method 1
,此method 1
應該返回某個類的對象。 對於我的return語句,我調用了另一個method 2
(該方法當然會返回所述類的對象)。 盡管此其他method 2
引發異常。 我應該如何在初始method 1
編寫return語句?
像這樣?
public class testClass {
public testClass() {
}
public <T> T method1(parameter1, ...) {
if(parameter1) {
return () -> {
try {
method2(parameter1, parameter2...);
}
catch (CloneNotSupportedException ex) {
System.err.print("Error while cloning programmer");
}
};
} else {
return null;
}
}
但是我想如果我這樣做只會返回null? 我應該在最后一個括號之后放置return null嗎? 還是我應該用完全不同的方式寫這個?
編輯。 你寫了
基本上,通常不應拋出異常
這是RuntimeException
的完美用例。 這基本上是一個透明的例外。 您的代碼用戶看不到它,但是當發生異常情況時,它看起來就像是一個狂野的Pokemon,它將使您的應用程序停止運行,從而有機會對其進行修復。
您的標准代碼流不會受到影響,並且您將避免返回null
值。
不允許Lambda表達式拋出經過檢查的Exception
。
CloneNotSupportedException
擴展了Exception
。
現在,您有兩個選擇
Exception
Exception
包裝在RuntimeException
傳播Exception
return () -> {
try {
method2(parameter1, parameter2...);
} catch (final CloneNotSupportedException e) {
throw YourCustomRuntimeException("Error while cloning", e /* Original cause */);
}
};
這取決於用例,但是我認為CloneNotSupportedException
發出一個bug ,對於開發人員您應該是顯而易見的。 所以讓它浮出水面。
自定義Exception
只需要擴展RuntimeException
,並且可能提供其他字段來存儲相關數據。
YourCustomRuntimeException extends RuntimeException { ... }
不要拋出基本的RuntimeException
,而要使用自定義的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.