Capturing exceptions in the execution of the swingworker

0

I'm using SwingWorker to execute a method that can throw exceptions. Even forcing, the exception is not caught by try-catch . How can I resolve this?

try {
    (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() {}
    }).execute();
    } catch (Exception ex) {
    JOptionPane.showMessageDialog(this, "Ocorreu um erro:n" + ex.getMessage(), "Erro ao salvar", JOptionPane.ERROR_MESSAGE);
}
    
asked by anonymous 23.04.2016 / 01:10

1 answer

1

Do not post doInBackground . run on a Thread apart from the (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.     

23.04.2016 / 01:30