我有下面的代碼。以下用例的Java異常處理
的問題是:
有沒有更好的方式來處理異常下面這以外的使用情況?
我特別感興趣的是使用handleException
方法。
public void checkSomeBehaviour() throws Exception{
try{
someBusinessValidation() ;
//this method can throw BusinessValidationException which is subclass of Exception
//BusinessValidationException contains code in getMessage() method
try{
doSomething();
}catch(Exception ex1){
//throw Exception object with specific error code say 123. So this needs to be wrapped in separate try/catch
throw CustomException('123'); //CustomException is subclass of Exception
}
try{
doSomethingElse();
}catch(Exception ex2){
//throw Exception object with specific error code say 456 .So this needs to be wrapped in separate try/catch
throw CustomException('456'); //CustomException is subclass of Exception
}
}
catch(Exception ex){
//Based on Exception type , a common exception needs to be thrown as ValidationException
handleException(ex);
}
}
//this method inspects exception type and does appropriate action accordingly
private void handleException(Exception ex){
if(ex instanceof CustomException){
throw new ValidationException(ex.getCode());
}else if(ex instanceof BusinessValidationException){
throw new ValidationException(ex.getMessage());
}else{
throw new ValidationException(100); //throw code as 100 since this is generalised exception
}
}
是的,我同意。但是提供一個通用的地方來處理異常是通過檢查異常類型來處理的,而不是在每個方法中檢查相同的捕獲原因?我們可以有許多這樣的方法來處理相同的異常處理 – Atul