Java:在异常消息中写入堆栈跟踪信息
我想用OtherException扩展Exception类,并在message字段中写入抛出类和方法的名称。除了使用父构造函数来设置消息之外,我看不到任何其他方法,但是我不能在super的参数中使用像getStackTrace这样的方法。有解决办法吗?或者有人知道为什么不能这样做吗 这是我想要的功能:Java:在异常消息中写入堆栈跟踪信息,java,exception,Java,Exception,我想用OtherException扩展Exception类,并在message字段中写入抛出类和方法的名称。除了使用父构造函数来设置消息之外,我看不到任何其他方法,但是我不能在super的参数中使用像getStackTrace这样的方法。有解决办法吗?或者有人知道为什么不能这样做吗 这是我想要的功能: public OtherException(final String message) { super(message + getStackTrace()[0].getClassName(
public OtherException(final String message) {
super(message + getStackTrace()[0].getClassName()+" "+getStackTrace()[0].getMethodName());
}
但它在Java中不起作用
这项工作:
public OtherException(final String message) {
super(message + " class: " + Thread.currentThread().getStackTrace()[2].getClassName() + ", method: "
+ Thread.currentThread().getStackTrace()[2].getMethodName());
}
也许有人知道一些更优雅的东西?据我所知,您希望将抛出异常的方法的名称作为异常的消息,不是吗? 在这种情况下,您的实现是正常的,只是我将它放入异常的默认构造函数中:
public OtherException() {
super(getStackTrace()[0].getClassName()+" "+getStackTrace()[0].getMethodName());
}
实际上,在构造函数中没有使用
message
参数,因此它是无用的。若您覆盖了默认构造函数,那个么您仍然能够实现其他构造函数,这些构造函数将接受消息并将其传递给super
,通常人们在创建自定义异常时会这样做 通常,您会在堆栈跟踪的异常中使用堆栈跟踪
public class OtherException extends Exception {
public OtherException(final String message) {
super(message);
}
}
OtherException oe = new OtherException("Hello");
StackTraceElement[] stes = oe.getStackTrace(); // get stack trace.
堆栈信息在创建异常时记录。实际的StackTraceeElement[]是在第一次使用时创建的。getStackTrace()是一个超类型方法,在调用super()之后才可用。对不起,我忘记了在super()的参数中写入消息。我认为最好只是为了有更多的灵活性。顺便说一下,我无法编译您的代码:“无法在显式调用构造函数时引用实例方法”。