我想使用OtherException擴展Exception類,並在消息字段中寫入拋出類和方法的名稱。除了使用父構造函數來設置消息之外,我看不到任何其他方法,但是我不能在超參數中使用像getStackTrace這樣的方法。任何解決方法?還是有人知道爲什麼不能這樣做?Java:在Exception消息中寫入StackTrace信息
這是我想擁有的功能:
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());
}
也許有人知道的東西更優雅?
雖然堆棧跟蹤在此處已填充? – biziclop 2012-03-12 13:40:33
getStackTrace()是一種超類型方法,直到super()被調用後纔可用。 – 2012-03-12 13:44:43
對不起,我忘了寫超級參數的消息。我認爲最好只是爲了增加靈活性。順便說一句,我不能編譯你的代碼:「在明確調用構造函數時不能引用實例方法」。 – 2012-03-12 13:58:56