2012-01-26 34 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 
相关问题