2017-05-20 39 views
0

我有下面的代碼。以下用例的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 
    } 

} 

回答

0

答案是:是的。 Java的爲您提供了原生的語法來做到這一點(清潔和簡單地比檢查更爲合適的異常類):

//...your try block 
} catch (CustomException ex) { 
    throw new ValidationException(ex.getCode()); 
} catch (BusinessValidationException ex) { 
    throw new ValidationException(ex.getMessage()); 
} catch (Exception ex) { 
    throw new ValidationException(100); 
} 

不過請注意,你可能需要,如果他們擴大彼此重新排列這些catch塊。

+0

是的,我同意。但是提供一個通用的地方來處理異常是通過檢查異常類型來處理的,而不是在每個方法中檢查相同的捕獲原因?我們可以有許多這樣的方法來處理相同的異常處理 – Atul

0

如果你沒有任何業務邏輯之間的方法調用,然後你可以聲明errorCode作爲變量,方法執行,並重新拋出適當的異常後改變它在catch,如:

public void checkSomeBehavior() throws Exception{ 
    int errorCode = 123; 
    try{ 
     someBusinessValidation(); 
     doSomething(); 
     errorCode = 456; 
     doSomethingElse(); 
    }catch(BusinessValidationException bve){ 
     throw new Exception(bve.getMessage()); 
    }catch(Exception e){ 
     throw new Exception(String.valueOf(errorCode)); 
    } 
} 

如果doSomething失敗,值將爲123,如果doSomethingElse失敗,則值將爲456.