Do not post doInBackground
. run on a Thread apart from the event-dispatch -thread (EDT). It is thanks to this that you can perform complex or heavy operations without the interface being locked waiting for the task to complete.
To catch possible exceptions thrown within doInBackground
, you can call the get()
inside the done()
method (which runs after the end of the parallel execution), and catch the exception within this method, since get()
returns the type of data that you set as a return in doInBackground
(in this case, it would be Void
) or an exception of type InterruptedException
(if Thread is interrupted) or ExecutionException
(if an exception was thrown inside of the execution of the doInBackground), and in done()
the execution returns to the Thread of the EDT:
(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 answer in SOen you have an excellent explanation of exceptions in SwingWorker
, it's worth giving a read.