How to throw a checked exception from a java thread?

Viewed 81994

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?

10 Answers

Use this Runnable to create your Thread:

public abstract class TryRunner implements Runnable{
    protected abstract void tryToRun();
    protected void onException(Exception e){}

    @Override 
    final public void run() { 
        try{ tryToRun(); }catch(Exception e){ e.printStackTrace(); onException(e); } 
    }
}
Related