[英]Add custom message to thrown exception while maintaining stack trace in Java
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;
}
}
}
尝试:
throw new Exception("transction: " + transNbr, E);
Exceptions are usually immutable: you can't change their message after they've been created. 例外通常是不可变的:您在创建消息后无法更改消息。 What you can do, though, is chain exceptions: 但是,您可以做的是链异常:
throw new TransactionProblemException(transNbr, originalException);
The stack trace will look like 堆栈跟踪看起来像
TransactionProblemException : transNbr
at ...
at ...
caused by OriginalException ...
at ...
at ...
There is an Exception
constructor that takes also the cause argument: Exception(String message, Throwable t) . 还有一个Exception
构造函数,它也带有cause参数: Exception(String message,Throwable t) 。
You can use it to propagate the stacktrace: 您可以使用它来传播堆栈跟踪:
try{
//...
}catch(Exception E){
if(!transNbr.equals("")){
throw new Exception("transaction: " + transNbr, E);
}
//...
}
you can use super while extending Exception 你可以在扩展Exception的同时使用super
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);
}
} }
} }
You can use your exception message by:- 您可以通过以下方式使用例外消息: -
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;
}
}
Following code is a simple example that worked for me.Let me call the function main
as parent function and divide
as child function. 下面的代码是一个适合我的简单示例。让我将函数main
作为父函数调用并divide
子函数。
Basically i am throwing a new exception with my custom message (for the parent's call) if an exception occurs in child function by catching the Exception in the child first. 基本上我正在使用我的自定义消息 (对于父级调用) 抛出一个新异常,如果子函数中发生异常,则首先在子级中捕获异常。
class Main {
public static void main(String args[]) {
try{
long ans=divide(0);
System.out.println("answer="+ans);
}
catch(Exception e){
System.out.println("got exception:"+e.getMessage());
}
}
public static long divide(int num) throws Exception{
long x=-1;
try {
x=5/num;
}
catch (Exception e){
throw new Exception("Error occured in divide for number:"+num+"Error:"+e.getMessage());
}
return x;
}
}
the last line return x
will not run if error occurs somewhere in between. 如果错误发生在两者之间,则最后一行return x
将不会运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.