我有一小段代码,可以运行一些事务进行处理。每笔交易都标有一个交易号,该交易号由外部程序生成,不一定要排序。当我在处理代码中捕获到异常时,我会将其抛出到主类中,并将其记录下来以供以后复查。我想将事务编号添加到这个抛出的异常中。有没有可能在保持正确的堆栈跟踪的同时做到这一点?
例如:
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;
}
}
}发布于 2012-09-24 23:41:29
尝试:
throw new Exception("transction: " + transNbr, E); 发布于 2012-09-24 23:44:13
异常通常是不可变的:您不能在创建它们之后更改它们的消息。但是,您可以做的是链异常:
throw new TransactionProblemException(transNbr, originalException);堆栈跟踪将如下所示
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...发布于 2012-09-24 23:42:59
还有一个带有原因参数的Exception构造函数:Exception(String message, Throwable t)。
您可以使用它来传播堆栈跟踪:
try{
//...
}catch(Exception E){
if(!transNbr.equals("")){
throw new Exception("transaction: " + transNbr, E);
}
//...
}https://stackoverflow.com/questions/12568340
复制相似问题