带有类名的exception.getMessage()输出

fre*_*crs 29 java exception-handling

我正在尝试修复一个问题,在我的应用程序中我有这个代码

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

而object1会做类似的事情:

public void method1() {
   //some code...
   throw new RuntimeException("Cannot move file");
}
Run Code Online (Sandbox Code Playgroud)

我的选项窗格中出现了这样一个消息: Error: java.lang.RuntimeException: Cannot move file

但是我使用的getMessage不是toString方法,所以不应该出现类的名称,对吧?

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

问题已解决 - 谢谢大家!

实际上是在SwingWorker的get()方法中调用了try和catch,它构造了一个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());
    }
}
Run Code Online (Sandbox Code Playgroud)

dac*_*cwe 30

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

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

...你会看到一个弹出窗口,说明你想要的.


但是,要解决您的问题(包装的异常),您需要使用"正确"消息进入"root"异常.为此,您需要创建一个自己的递归方法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;
}
Run Code Online (Sandbox Code Playgroud)

注意:然而,解开这样的异常会破坏抽象.我鼓励你找出异常被包装的原因并问自己是否有意义.

  • 我不同意.我*从来没有*遇到这种情况.实际上,考虑到`printStackTrace`方法,即使是`Throwable`类的设计者也不考虑这种情况. (3认同)

Jon*_*eet 6

我的猜测是你有一些东西在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");
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Error: Just the message
Run Code Online (Sandbox Code Playgroud)