在Java中维护堆栈跟踪的同时向抛出异常添加自定义消息

the*_*dan 51 java exception-handling exception

我有一小段代码贯穿一些事务处理.每个事务都标有一个事务编号,该事务编号由外部程序生成,不一定按顺序排序.当我在处理代码中捕获异常时,我将它抛到主类并将其记录下来以供稍后查看.我想将事务编号添加到此抛出的异常中.是否可以在保持正确的堆栈跟踪的同时执行此操作?

例如:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bor*_*vić 86

尝试:

throw new Exception("transction: " + transNbr, E); 
Run Code Online (Sandbox Code Playgroud)

  • 按照 Java 的惯例,实例是小写的。 (4认同)

JB *_*zet 13

例外通常是不可变的:您在创建消息后无法更改消息.但是,您可以做的是链异常:

throw new TransactionProblemException(transNbr, originalException);
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪看起来像

TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
Run Code Online (Sandbox Code Playgroud)

  • 这更好,因为异常类名与域相关联 - 可以立即准确地识别出问题的根源。加上代码分析工具可能会在您`throw new Exception(...)` 时引发警告。 (2认同)

dce*_*chi 8

还有一个Exception构造函数也接受cause参数:Exception(String message,Throwable t).

您可以使用它来传播堆栈跟踪:

try{
    //...
}catch(Exception E){
    if(!transNbr.equals("")){
        throw new Exception("transaction: " + transNbr, E); 
    }
    //...
}
Run Code Online (Sandbox Code Playgroud)