线程中抛出错误(异常)
问题描述:
我正在研究一个简单的Java应用程序。我有抛出异常的问题。线程中抛出错误(异常)
实际上,应该在线程中抛出异常。所以有这些例外的线程:
public void setVyplata(Otec otec) {
try {
otec.setVyplata(Integer.parseInt(textField1.getText()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
otec.setVyplata(0);
textField1.setText("0");
}
}
public void setVyplata(Mama mama) {
try {
mama.setVyplata(Integer.parseInt(textField2.getText()));
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
mama.setVyplata(0);
textField2.setText("0");
}
}
这是可能的,两个例外将同时抛出。
而且当它,这就是我得到:
我有线程运行的每个方法。我的问题是为什么程序会停止在这里工作。因为,当我分开启动这些线程之一。它完美地工作。当我开始这两个线程应该有2个错误窗口,但你可以看到空白的错误窗口和程序无法正常工作。
答
我可以明确告诉你,根据你以前的评论,你有一个问题,没有线程安全摆动组件的特点。您应该阅读The Event Dispatch Thread文档。您需要使用调用方法来确保您的更改任务放置在事件派发线程上,否则,您的应用程序会崩溃。
为您的代码示例:
public void setVyplata(Otec otec) {
try {
otec.setVyplata(Integer.parseInt(textField1.getText()));
} catch (NumberFormatException e) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
otec.setVyplata(0);
textField1.setText("0");
});
}
}
public void setVyplata(Mama mama) {
try {
mama.setVyplata(Integer.parseInt(textField2.getText()));
} catch (NumberFormatException e) {
SwingUtilities.invokeLater(() -> {
JOptionPane.showMessageDialog(panel, "Nemozno vlozit string", "Error", JOptionPane.ERROR_MESSAGE);
mama.setVyplata(0);
textField2.setText("0");
});
}
}
如果SwingUtilities类的文档中查找你有什么invokeLater一个很好的解释其实就是做:
导致doRun.run()来在调度线程的AWT事件 上异步执行。在处理了所有待处理的AWT事件 之后,会发生这种情况。应用程序线程 需要更新GUI时应使用此方法。在以下示例中,invokeLater调用 会将事件调度 线程中的Runnable对象doHelloWorld排队,然后打印消息。
+2
非常感谢:)这节省了我的一天:) –
你的问题是什么? – Vijay
是不是你有一个针对每种方法运行的线程,并且你需要在某个地方得到这个异常,或者你只需要知道你是否有两个对话?或者进一步说,当两个线程都在运行时,你实际上是想在同一个对话中捕获这两个错误? –
你为了不中断程序的执行而捕获异常,所以当你捕捉到异常时你只会中断那个方法的执行,你有两种不同的方法,所以你会捕获两个不同的异常 –