exception.getMessage() output with class name

前端 未结 2 457
天涯浪人
天涯浪人 2020-12-16 10:03

I\'m trying to fix an issue, in my application I have this code

try {
  object1.method1();
} catch(Exception ex) {
   JOptionPane.showMessageDialog(nulll, \"         


        
2条回答
  •  庸人自扰
    2020-12-16 10:19

    I think you are wrapping your exception in another exception (which isn't in your code above). If you try out this code:

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

    ...you will see a popup that says exactly what you want.


    However, to solve your problem (the wrapped exception) you need get to the "root" exception with the "correct" message. To do this you need to create a own recursive method 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;
    }
    

    Note: Unwrapping exceptions like this however, sort of breaks the abstractions. I encourage you to find out why the exception is wrapped and ask yourself if it makes sense.

提交回复
热议问题