Capture exceptions in swingworker execution

Asked

Viewed 108 times

0

I’m using SwingWorker to execute a method that can throw exceptions.
Even forcing, the exception is not captured by Try-catch. How can I solve this case?

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);
}

1 answer

1


Don’t throw the doInBackground runs in a Thread apart from (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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.