SwingWorker exceptions lost even when using wrapper classes

后端 未结 3 1551
走了就别回头了
走了就别回头了 2021-02-02 02:11

I\'ve been struggling with the usability problem of SwingWorker eating any exceptions thrown in the background task, for example, described on this SO thread. That thread gives

3条回答
  •  礼貌的吻别
    2021-02-02 02:51

    Forget about your wrapper, which eats the exceptions, whereas the SwingWorker doesn't. Here's how a SwingWorker should be used, and how you should handle a specific exception thrown from the background task:

    class MeaningOfLifeFinder extends SwingWorker {
        @Override
        public String doInBackground() throws SomeException {
            return findTheMeaningOfLife();
        }
    
        @Override
        protected void done() { // called in the EDT. You can update the GUI here, show error dialogs, etc.
            try { 
                String meaningOfLife = get(); // this line can throw InterruptedException or ExecutionException
                label.setText(meaningOfLife);
            } 
            catch (ExecutionException e) {
                Throwable cause = e.getCause(); // if SomeException was thrown by the background task, it's wrapped into the ExecutionException
                if (cause instanceof SomeException) {
                    // TODO handle SomeException as you want to
                }
                else { // the wrapped throwable is a runtime exception or an error
                    // TODO handle any other exception as you want to
                }
            }
            catch (InterruptedException ie) {
                // TODO handle the case where the background task was interrupted as you want to
            }
        }
    }
    

提交回复
热议问题