带有类名的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
- Java中的类IOException是否是未经检查的RuntimeException?
- 无限循环当在try-catch块中捕获InputMidmatchException时
- 如何在调用Thread.sleep()时修复未处理exception的编译错误?
- Java的exception处理机制是责任链设计模式的一个例子吗?
- Spring MVC最佳实践处理控制器中不可恢复的exception
- 使用Scanner.nextInt()与Scanner.nextLine()进行exception处理
- 为什么订单在捕获exception时很重要?
- Java Mail超时和connectiontimeout处理
- Struts2exception处理用法?