In Java thread, the 'run' method cannot throw a 'checked exception'. I came across this in the Core Java (vol 1) book. Can someone please explain the reasoning behind it?
In Java thread, the 'run' method cannot throw a 'checked exception'.
the thread can't throw the exception to any other thread (nor to the main thread). and you cannot make the inherited run() method throw any checked exceptions since you can only throw less than the inherited code, not more.
If there is an exception handler installed for the ThreadGroup, the JVM passes the exception to it. If it's an AWT thread, you can install an event handler for otherwise unhandled exceptions. Otherwise the JVM handles it.
Runnable can't throw checked exception but RuntimeException can be thrown from the run(). Uncaught exceptions are handled by the exception handler of the thread, if JVM can't handle or catch exceptions, it prints the stack trace and terminates the flow.
Can someone please explain the reasoning behind it?
Yes, because any exception you throw in run
method will be carefully ignored by JVM. Thus, throwing it there is probably a mistake (unless you have specific exception handler for the thread, see the docs about that). No reason to incite potentially erroneous behaviour.
Or, with an example.
class MyThread extends Thread { public void run() { throw new RuntimeException(); } } ... new MyThread().start(); // here thread dies silently with no visible effects at all
edit
Why can't the parent thread 'catch' the exception from the spawned 'child' thread?
@chaotic3quilibrium has already noted in his comment why not: because parent thread has likely moved on already.
new MyThread().start(); // launch thread and forget // 1000 lines of code further... i = i + 1; // would you like exception from child thread to be propagated here?
What would catch the exception and handle it? Let's assume that the run method could throw a checked exception. Then you could write code like this:
Thread myThread = new Thread(aRunnable); try{ myThread.start(); } catch(Exception e){ e.printStackTrace(); } //do other stuff
BUT once you call myThread.start
, the new thread is started in the background and the current thread continues and exits the try-catch and does other stuff. So if myThread
did throw an exception later on, you can't catch it!
What you need to do is deal with the exception within the run
method and then probably have a way of notifying another object that this thread failed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With