2012-09-24 38 views
33

我有一小段代碼在某些要處理的事務中運行。每筆交易都標有一個交易號碼,該號碼由外部程序生成,不一定按順序排列。當我在處理代碼中捕獲一個異常時,我將它扔到主類並記錄下來以供日後查看。我想將交易號添加到此拋出的異常。是否可以在保持正確的堆棧跟蹤的同時執行此操作?將自定義消息添加到拋出的異常,同時在Java中維護堆棧跟蹤

例如:

public static void main(String[] args) { 
    try{ 
     processMessage(); 
    }catch(Exception E){ 
     E.printStackTrace(); 
    } 

} 

private static void processMessage() throws Exception{ 
    String transNbr = ""; 
    try{ 
     transNbr = "2345"; 
     throw new Exception(); 
    }catch(Exception E){ 
     if(!transNbr.equals("")){ 
      //stack trace originates from here, not from actual exception 
      throw new Exception("transction: " + transNbr); 
     }else{ 
      //stack trace gets passed correctly but no custom message available 
      throw E; 
     } 
    } 
} 

回答

56

嘗試:

throw new Exception("transction: " + transNbr, E); 
+1

這正是我一直在尋找。謝謝。 – thedan

6

有一個Exception構造函數,也需要原因的說法:Exception(String message, Throwable t)

你可以用它來傳播堆棧跟蹤:

try{ 
    ... 
}catch(Exception E){ 
    if(!transNbr.equals("")){ 
     throw new Exception("transction: " + transNbr, E); 
    } 
    ... 
} 
12

異常通常是不可變的:創建完成後,您無法更改其消息。你能做什麼,雖然是連鎖例外:

throw new TransactionProblemException(transNbr, originalException); 

堆棧跟蹤看起來像

TransactionProblemException : transNbr 
at ... 
at ... 
caused by OriginalException ... 
at ... 
at ... 
+1

這樣更好,因爲異常類名與域綁定在一起 - 它立即可以識別問題的根源。加上代碼分析工具可能會在拋出新的異常(...)'時引發警告。 – vikingsteve

0

您可以使用您的異常消息: -

public class MyNullPointException extends NullPointerException { 

     private ExceptionCodes exceptionCodesCode; 

     public MyNullPointException(ExceptionCodes code) { 
      this.exceptionCodesCode=code; 
     } 
     @Override 
     public String getMessage() { 
      return exceptionCodesCode.getCode(); 
     } 


    public class enum ExceptionCodes { 
    COULD_NOT_SAVE_RECORD ("cityId:001(could.not.save.record)"), 
    NULL_POINT_EXCEPTION_RECORD ("cityId:002(null.point.exception.record)"), 
    COULD_NOT_DELETE_RECORD ("cityId:003(could.not.delete.record)"); 

    private String code; 

    private ExceptionCodes(String code) { 
     this.code = code; 
    } 

    public String getCode() { 
     return code; 
    } 
} 
1

可以使用超級,同時延長例外

if (pass.length() < minPassLength) 
    throw new InvalidPassException("The password provided is too short"); 
} catch (NullPointerException e) { 
    throw new InvalidPassException("No password provided", e); 
} 


// A custom business exception 
class InvalidPassException extends Exception { 

InvalidPassException() { 

} 

InvalidPassException(String message) { 
    super(message); 
} 
InvalidPassException(String message, Throwable cause) { 
    super(message, cause); 
} 

}

}

source

相關問題