Don’t throw the doInBackground
runs in a Thread apart from Event-Dispatch-thread (EDT). It is thanks to this that you can perform complex or heavy operations without the interface being locked and waiting for the task to be completed.
To capture possible exceptions launched within the doInBackground
, you can call the method get()
within the method done()
(which is executed after the end of the parallel execution), and capture the exception within this method, as the get()
returns the type of data you set to return on doInBackground
(in your case, it would be Void
) or an exception of the type InterruptedException
(if Thread is interrupted) or ExecutionException
(whether an exception has been made within the execution of the done()
the execution is back in the EDT thread:
(new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws InterruptedException, Exception {
// Pode lançar exceções
Controller.getInstance().save(d);
return null;
}
@Override
protected void done() {
try{
get();
}catch(ExecutionException e){
JOptionPane.showMessageDialog(this, "Ocorreu um erro:\n" + ex.getMessage(), "Erro ao salvar", JOptionPane.ERROR_MESSAGE);
}catch(InterruptedException e){
//catch opcional se quiser tratar a interrupção
// da thread da tarefa paralela
}
}
}).execute();
In this reply on Soen has an excellent explanation of exceptions in SwingWorker
, is worth a read.