[英]Custom Exception Class - Shall I extend Runtime Exception OR Exception?
任何人都可以指導我是否應擴展Exception或RuntimeException?
通常,它用於驗證,意外異常,自定義異常,業務邏輯失敗時引發等。
下面是我的自定義異常類。
/**
* The class <code>BaseException</code> is a custom exception class.
* @author Pratiyush Kumar Singh
*/
public class BaseException extends Exception {
static final long serialVersionUID = -3387516993124229948L;
/**
* Constructs a new exception.
*/
public BaseException() {
super();
}
/**
* Constructs a new exception with the specified detail message.
* @param message - It contains the error message.
*/
public BaseException(String message) {
super(message);
}
/**
* Constructs a new exception with the specified detail message.
* @param message - It contains the error message.
* @param cause - Instance of Throwable.
*/
public BaseException(String message, Throwable cause) {
super(message, cause);
}
}
有人說自定義異常是一種代碼味道。 您當然不應該有太多。
Java的原始默認設置為檢查異常。 設計人員反對C返回代碼約定,因為他們不喜歡開發人員可以忽略它們的想法。 已檢查的異常要求要捕獲並處理。
C#朝另一個方向發展,並首選未經檢查的異常。 發現帶有try / catch的亂碼很麻煩。
您應該根據需要決定是擴展Exception
(選中)還是RuntimeException
(選中)。 問自己:我是否應該強迫開發人員應對這種情況?
或者,您可以遵循時尚並使其不受控制。
我建議您盡可能使用JDK中的現有類。
編譯器不需要客戶端處理RuntimeException ,而需要Exception
。 因此,如果要強制客戶端編寫嘗試從條件中恢復的代碼,則應從Exception擴展,否則,則應從RuntimeException擴展。
下面是一個示例,說明如果不從RuntimeException擴展,客戶端將必須如何處理。
void foo() throws MyException(); // throw up the stack
void foo() { // handle exception with try-catch
try {
}
catch (MyException e) {
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.