簡體   English   中英

Java Throwing RuntimeException有什么好處

[英]Java what is the benefit of Throwing RuntimeException

聲明(Unchecked Exception)沿方法簽名b / c拋出異常的好處是,它不會強制調用者保留在try catch塊中。

public void testRuntimeEx()throws RuntimeException{

if(1==1){throw new RuntimeException()}

}

//Caller method
public void testCaller(){
// not necessery to handle even caller does not known which RuntimeException might be throws then what is the benefit throws clause with method signature
testRuntimeEx(); 

}

它仍然充當文檔,特別是如果您不使用通用的RuntimeException,而是更具體的東西,例如IllegalArgumentException或UnsupportedOperationExceptionIndexOutOfBoundsException,並且還添加了有關何時發生的JavaDoc。

但是,在您的示例代碼片段中,它是毫無意義的。

該聲明是使用此代碼的開發人員的信號,它拋出RuntimeException。 但它聞起來不好。

您發布的PS代碼將無法編譯:

throw RuntimeException

這是不正確的投擲。

好處是通常調用者與異常無關。 它捕獲它,並包裝其他異常然后再次拋出。 或者,也可以使用throws關鍵字聲明異常,並在出現異常時對該類型透明。

我要說的是,上述情況對於我們通常編寫業務代碼並在一個集中處理所有異常的地方的應用程序來說是典型的。 API不正確。 例如,如果您使用的是實現SSH的庫,則您期望當出現問題時它會引發IOException (或更特殊的異常)。

如果引發自定義未檢查的異常,它將變得更有意義,而不是捕獲系統異常,而未檢查的異常也不會強制捕獲。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM