javaexceptionthread-exceptions

How to throw a checked exception from a java thread?


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 is, that the compiler doesn't let me to put any code throwing (checked) exceptions into run(). It says:

run() in (...).Listener cannot implement run() in java.lang.Runnable; overridden method does not throw java.io.IOException

I want the exception to kill the thread, and let it be caught somewhere in the parent thread. Is this possible to achieve or do I have to handle every exception inside the thread?


Solution

  • 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.