SwingWorker exceptions lost even when using wrapper classes

后端 未结 3 1544
走了就别回头了
走了就别回头了 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 02:53

    I think everyone is making this too complicated. Just try this:

    String myResult="notSet";
    try {
        // from your example above
        helper.execute();  // this will call get+done on the actual worker
        myResult=helper.get();
    } catch (Exception e) {
    // this section will be invoked if your swingworker dies, and print out why...
         System.out.println("exception ");
         e.printStackTrace() ;
         myResult="Exception "+e.getMessage();
    }
    return myResult;
    

    The exceptions you throw but get eaten will be revealed. Two points will explain why this works. One, you only catch the remote exception from the calling thread whem you .get() the result. In more detail: To make the above example asynchronous, just move the .execute() higher up in the code. The moment you will discover the remote exception is after the asynch thread has bombed and you .get() the result. Two, by catching all Exceptions you will catch all special and subclassed exceptions that you may have built which the calling program may not have known about.

提交回复
热议问题