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)
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)
还有一个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)