exception.getMessage()输出与类名 [英] exception.getMessage() output with class name
问题描述
我正在尝试解决一个问题,在我的应用程序中我有这个代码
I'm trying to fix an issue, in my application I have this code
try {
object1.method1();
} catch(Exception ex) {
JOptionPane.showMessageDialog(nulll, "Error: "+ex.getMessage());
}
,对象1将执行以下操作:
and the object1 would do something like that:
public void method1() {
//some code...
throw new RuntimeException("Cannot move file");
}
我在我的选项窗格中收到如下错误消息:
错误:java.lang.RuntimeException:无法移动文件
I get a messsage in my option pane like this:
Error: java.lang.RuntimeException: Cannot move file
但我使用 getMessage
而不是
toString
方法,所以类的名称不应该出现,对吗?
but I used getMessage
and not toString
method, so the name of the class shouldn´t appear, right?
我已经尝试了很多例外,甚至 Exception
本身。我正在寻求解决这个问题,而无需实现我自己的异常
子类
What I am doing wrong?
I already tryied with a lot of exceptions, even Exception
itself. I'm looking to solve this no without the need to implement my own Exception
subclass
解决问题 - 感谢大家!
从SwingWorker的 get()方法中,try和catch实际上被调用, code> ExecutionException 我从 doInBackground()抛出我的异常
我修复了这样做:
The try and catch were actually being called in get() method from SwingWorker which constructs an ExecutionException
with my exception thrown from doInBackground()
I fixed doing this:
@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());
}
}
推荐答案
认为你正在将异常包装在另一个异常中(这不在你的代码上面)。如果您尝试以下代码:
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.
但是,为了解决你的问题(包装的异常),你需要得到根异常与正确的消息。为此,您需要创建一个自己的递归方法 getRootCause
:
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;
}
注意:解开这样的异常, 。我鼓励你找出为什么例外被包装,问问自己是否有意义。
这篇关于exception.getMessage()输出与类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!