2012-01-26 35 views
18

我試圖解決的問題,在我的應用我有這樣的代碼exception.getMessage()使用類名稱輸出

try { 
    object1.method1(); 
} catch(Exception ex) { 
    JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage()); 
} 

和object1會做這樣的事情:

public void method1() { 
    //some code... 
    throw new RuntimeException("Cannot move file"); 
} 

我收到了一封郵件在我的選項窗格是這樣的: Error: java.lang.RuntimeException: Cannot move file

但我用getMessage而不是toString方法,因此該類SH名不會出現,對嗎?

我做錯了什麼? 我已經嘗試了很多例外,即使是Exception本身。我正在尋求解決這個問題,如果沒有必要實施我自己的Exception子類

問題解決 - 謝謝大家!

try和catch實際上被稱爲的get()從SwingWorker的方法,構建與我異常的ExecutionExceptiondoInBackground()拋出 我固定這樣做:

@Override 
protected void done() { 
    try { 
     Object u = (Object) get(); 
     //do whatever u want 
    } catch(ExecutionException ex) { 
     JOptionPane.showMessageDialog(null, "Error: "+ex.getCause().getMessage()); 
    } catch(Exception ex) { 
     JOptionPane.showMessageDialog(null, "Error: "+ex.getMessage()); 
    } 
} 
+1

聽起來很奇怪 - 你能在很短,但完整的程序重現此? –

+0

你可以在'catch'中添加'e.printStackTrace()'嗎?看起來@dacwe是對的。 –

+0

看着堆棧跟蹤我可以看到問題可能是Swing Worker ....... try {}實際上是從swing worker方法done()調用get(),並拋出異常拋出doInBackGround – fredcrs

回答

24

我認爲你正在用另一個異常(這不在你的代碼中)包裝你的異常。如果您嘗試使用此代碼:

public static void main(String[] args) { 
    try { 
     throw new RuntimeException("Cannot move file"); 
    } catch (Exception ex) { 
     JOptionPane.showMessageDialog(null, "Error: " + ex.getMessage()); 
    } 
} 

...您會看到一個彈出窗口,顯示您想要的內容。


但是,要解決您的問題(包裝的異常),您需要使用「正確」消息進入「根」異常。要做到這一點,你需要創建一個自己的遞歸方法getRootCause

public static void main(String[] args) { 
    try { 
     throw new Exception(new RuntimeException("Cannot move file")); 
    } catch (Exception ex) { 
     JOptionPane.showMessageDialog(null, 
             "Error: " + getRootCause(ex).getMessage()); 
    } 
} 

public static Throwable getRootCause(Throwable throwable) { 
    if (throwable.getCause() != null) 
     return getRootCause(throwable.getCause()); 

    return throwable; 
} 

注:解包異常喜歡這個然而,那種打破了抽象。我鼓勵你找出異常被包裹的原因,並問問你自己是否有意義。

+0

您的getRootCause方法未受到無限遞歸保護。 – Perception

+0

@Perception,除非throwable本身是它的原因,否則你有其他一些超級怪異的循環鏈因素,你不需要擔心它。 – aioobe

+0

@aioobe - 確實,這些是檢查的主要原因。但這並不像你想象的那樣罕見。 – Perception

5

我的猜測是,你有在method1它包裝在一個又一個例外的東西,並使用嵌套的例外,因爲包裝的消息toString()。我建議你拿一份你的項目的副本,並在保留問題的同時儘可能多地刪除,直到你有一個簡短但完整的程序來演示它 - 這時要麼清楚發生了什麼,要麼我們將能夠更好地幫助解決問題。

下面是這表明RuntimeException.getMessage()一個簡短而完整的程序正確行爲:

public class Test { 
    public static void main(String[] args) { 
     try { 
      failingMethod(); 
     } catch (Exception e) { 
      System.out.println("Error: " + e.getMessage()); 
     } 
    }  

    private static void failingMethod() { 
     throw new RuntimeException("Just the message"); 
    } 
} 

輸出:

Error: Just the message 
相關問題