How to throw a checked exception from a java thread?

后端 未结 9 2165
长发绾君心
长发绾君心 2020-11-28 04:45

Hey, I\'m writing a network application, in which I read packets of some custom binary format. And I\'m starting a background thread to wait for incoming data. The problem i

9条回答
  •  日久生厌
    2020-11-28 05:12

    Caveat: this may not meet your needs if you have to use the exception mechanism.

    If I understand you correctly, you don't actually need the exception to be checked (you've accepted the answer suggesting an unchecked exception) so would a simple listener pattern be more appropriate?

    The listener could live in the parent thread, and when you've caught the checked exception in the child thread, you could simply notify the listener.

    This means that you have a way of exposing that this will happen (through public methods), and will be able to pass more information than an exception will allow. But it does mean there will be a coupling (albeit a loose one) between the parent and the child thread. It would depend in your specific situation whether this would have a benefit over wrapping the checked exception with an unchecked one.

    Here's a simple example (some code borrowed from another answer):

    public class ThingRunnable implements Runnable {
        private SomeListenerType listener;
        // assign listener somewhere
    
        public void run() {
            try {
                while(iHaveMorePackets()) { 
                    doStuffWithPacket();
                }
            } catch(Exception e) {
                listener.notifyThatDarnedExceptionHappened(...);
            }
        }
     }
    

    The coupling comes from an object in the parent thread having to be of type SomeListenerType.

提交回复
热议问题