[英]Java: write StackTrace info in Exception message
我想用OtherException擴展Exception類,並在message字段中寫出throwing類和方法的名稱。 除了使用父構造函數設置消息外,我看不到其他任何方式,但是我不能在super的參數中使用諸如getStackTrace之類的方法。 任何解決方法? 還是有人知道為什么不能做到這一點?
這是我想要的功能:
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.
在創建異常時記錄堆棧信息。 實際的StackTraceElement []是在第一次使用時創建的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.