Throwable(and catch)Throwable(或Exception)通常是不好的做法,因爲它會覆蓋你可能想要捕捉的任何特定異常。然後,你將不得不求助於醜象下面這樣:
public void myMethod() throws Throwable {
if (x) {
throw new MyException1();
}
if (y) {
throw new MyException2();
}
}
public void callingMethod() {
try {
myMethod();
}
catch(Throwable t) {
if (t instanceof MyException1) {
// handle exception 1
}
else if (t instanceof MyException2) {
// handle exception 2
}
else {
// handle other exceptions
}
}
}
這是容易出錯(和CheckStyle的標記作爲代碼違例)。這是很preferrable有這樣的代碼:只要通過喚起的printStackTrace(
public void myMethod() throws MyException1, MyException2 {
if (x) {
throw new MyException1();
}
if (y) {
throw new MyException2();
}
}
public void callingMethod() {
try {
myMethod();
}
catch(MyException1 e) {
// handle exception 1
}
catch(MyException2 e) {
// handle exception 2
}
}
處理異常)通常不是一個好主意。 printStackTrace()將堆棧跟蹤發送到標準錯誤,根本不可讀取。更好的選擇是使用應用程序的日誌工具(如log4j)來報告異常。即使那樣,只是記錄它可能是不夠的。
我的經驗法則是:
如果你可以在本地處理異常,這樣做。例如解析字符串爲整數,你可以趕上NumberFormatException異常,並返回默認值時:
prvate int parseAmount(String amountValue) {
int amount;
try {
amount = Integer.parseInt(amountValue);
}
catch(NumberFormatException e) {
// default amount
amount = 0;
}
return amount;
}
如果你不能處理本地異常,考慮是否應公開正被拋出的異常類型。如果這個類型是一些不起眼的(實現相關的)類型,然後在自己的泛型類型的異常包裹它可能是一個好主意:
private Customer getCustomer(int customerId) throws ServiceException {
try {
return customerService.getCustomer(customerId);
}
catch(CustomerServiceSpaghettiTangledException e) {
throw new ServiceException("Error calling the customer service", e);
}
}
這裏ServiceException「是您創建異常的子類。 Spring還專門爲此提供了一個exception hierarchy。
通過包裝異常,您可以隱藏實現細節,使您的服務層更簡單易用。
如果你決定從你的方法拋出異常,你需要在callstack中'更高'處理它。這可能是Web應用程序中的一個通用錯誤頁面,指出發生錯誤並可能提供錯誤消息或代碼。在某些情況下,較高級別的代碼可以嘗試重試或可能以其他方式獲得所需的結果。
可能這會給你一個解釋:http://stackoverflow.com/questions/498217/when-should-throwable-be-used-instead-of-new-exception – Serge
「throws Throwable」更常用於SDK和框架定義。以下是Android測試框架中使用它的一個示例:http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.4.2_r1/android/test/ InstrumentationTestCase.java#InstrumentationTestCase –