简体   繁体   中英

Java: write StackTrace info in Exception message

I want to extend the Exception class with OtherException and write the name of the throwing class and method in the message field. I cannot see any way other than using the parent constructor in order to set the message, but I cannot use methods like getStackTrace in the argument of super. Any workarounds? Or does anybody know why this cannot be done?

This is the functionality that I would like to have:

public OtherException(final String message) {
    super(message + getStackTrace()[0].getClassName()+" "+getStackTrace()[0].getMethodName());
}

but it does not work in Java.

This works:

public OtherException(final String message) {
    super(message + " class: " + Thread.currentThread().getStackTrace()[2].getClassName() + ", method: "
            + Thread.currentThread().getStackTrace()[2].getMethodName());
}

Maybe somebody knows something more elegant?

As far as I understand you want to have the name of method where exception was thrown as the exception's message, don't you? In this case you implementation is ok, just I'd put it into default constructor of your exception:

public OtherException() {
    super(getStackTrace()[0].getClassName()+" "+getStackTrace()[0].getMethodName());
}

Really, you do not use message argument in your constructor, so it is useless. And if you override default constructor you are still able to implement other constructors that will accept message and pass it to super usually people do when they create custom exceptions.

Normally you would use the stack trace in the Exception for the stack trace.

public class OtherException extends Exception {
    public OtherException(final String message) {
        super(message);
    }
}

OtherException oe = new OtherException("Hello");
StackTraceElement[] stes = oe.getStackTrace(); // get stack trace.

the stack information is recorded at the point the Exception is created. The actual StackTraceElement[] is created the first time it is used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM