在Java中保持堆栈跟踪时,添加自定义消息以抛出异常 [英] Add custom message to thrown exception while maintaining stack trace in Java

查看:235
本文介绍了在Java中保持堆栈跟踪时,添加自定义消息以抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一小段代码可以通过一些交易进行处理。每个交易都标有一个交易号码,由一个外部程序生成,不一定是顺序的。当我在处理代码中捕获异常时,我把它抛给主类,然后再记录下来进行审查。我想将事务号添加到这个抛出的异常中。



例如:

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

}

private static void processMessage()throws异常{
String transNbr =;
try {
transNbr =2345;
throw new Exception();
} catch(Exception E){
if(!transNbr.equals()){
//堆栈跟踪起源于这里,而不是实际异常
throw new Exception (transction:+ transNbr);
} else {
//堆栈跟踪正确传递,但没有自定义消息
throw E;
}
}
}


解决方案

尝试:

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


I have a small piece of code that runs through some transactions for processing. Each transaction is marked with a transaction number, which is generated by an outside program and is not necessarily sequenced. When I catch an Exception in the processing code I am throwing it up to the main class and logging it for review later. I'd like to add the transaction number to this thrown Exception. Is it possible to do this while still maintaining the correct stack trace?

For Example:

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;
        }
    }
}

解决方案

Try:

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

这篇关于在Java中保持堆栈跟踪时,添加自定义消息以抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆