简体   繁体   English

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

[英]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);
}

} }

} }

source 资源

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.

相关问题 java.lang.ArithmeticException 抛出没有堆栈跟踪和消息 - java.lang.ArithmeticException thrown without stack trace and without message Java中自定义异常抛出的消息中的断行 - Break line in message thrown by custom Exception in Java 为所有测试类设置自定义 TestExecutionListener,因此我可以记录抛出的每个异常/断言的堆栈跟踪 - Setting custom TestExecutionListener for all test classes, so I can log the stack trace of every exception/assertion thrown Java 错误:catch 块中抛出新异常,原始堆栈跟踪可能丢失 - Java error: New exception is thrown in catch block, original stack trace may be lost Java中没有堆栈跟踪的异常 - Exception without stack trace in Java 为什么我的Java异常在SwingWorker中抛出时不会打印堆栈跟踪? - Why doesn't my Java exception print a stack trace when thrown inside a SwingWorker? Java异常处理和堆栈跟踪 - Java Exception Handling and Stack Trace 如何停止EJBException的堆栈跟踪(在每个抛出的Exception中) - How to stop EJBException's stack trace (in every thrown Exception) 多次抛出相同异常后省略堆栈跟踪 - Omit stack trace after same exception is thrown several times 如何查找Swing组件抛出的未知异常的(信息性)堆栈跟踪 - How to find an (informative) stack trace of unknown exception thrown by Swing components
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM