带有类名的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方法,所以不应该出现类的名称,对吧?

我做错了什么? 我已经尝试了很多例外,甚至是Exception本身。 我希望解决这个问题,而不需要实现我自己的Exception子类

问题已解决 – 谢谢大家!

实际上是在SwingWorker的get()方法中调用了try和catch,它构造了一个ExecutionException ,我从doInBackground抛出exception()我修复了这样做:

 @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()); } } 

我认为你将exception包装在另一个exception中(不在上面的代码中)。 如果你试试这个代码:

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

…你会看到一个弹出窗口,说明你想要的内容。


但是,要解决您的问题(包装的exception),您需要使用“正确”消息进入“root”exception。 要做到这一点,你需要创建一个自己的递归方法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; } 

注意:然而,解开这样的exception会破坏抽象。 我鼓励你找出为什么包含exception,并问自己是否有意义。

我的猜测是你在method1中有一些东西在另一个exception中包含一个exception,并使用嵌套exception的toString()作为包装器的消息。 我建议你复制你的项目,尽可能多地删除,同时保留问题,直到你得到一个简短但完整的程序来certificate它 – 此时要么清楚发生了什么,要么我们将处于更有利的位置来帮助修复它。

这是一个简短但完整的程序,它演示了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