2012-03-12 23 views
0

我想使用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()); 
} 

也許有人知道的東西更優雅?

回答

0

據我瞭解,你想擁有異常被拋出的方法的名稱作爲異常的消息,不是嗎? 在這種情況下,你的實現是好的,只是我把它變成你的異常的默認構造函數:

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

真的,你不要在你的構造函數中使用message說法,所以也沒用。如果你重寫默認構造函數,你仍然可以實現其他構造函數,它們將接受消息並將它傳遞給super,通常人們在創建自定義異常時會這樣做。

+0

雖然堆棧跟蹤在此處已填充? – biziclop 2012-03-12 13:40:33

+1

getStackTrace()是一種超類型方法,直到super()被調用後纔可用。 – 2012-03-12 13:44:43

+0

對不起,我忘了寫超級參數的消息。我認爲最好只是爲了增加靈活性。順便說一句,我不能編譯你的代碼:「在明確調用構造函數時不能引用實例方法」。 – 2012-03-12 13:58:56

0

通常情況下,您會在堆棧跟蹤的異常中使用堆棧跟蹤。

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 []。