Why we can not throw exception from Thread’s run method?

Yes, you heard it right. We cannot throw checked exceptions from our implemented threads run() method. Because we override Thread class’s or Runnable interface’s run() method and that method does not throw any checked exception and that’s why even we cannot throw checked exception in our overriding run() method (“Rules for method overriding” is a different topic to discuss, that I will cover separately).

Now a big question comes to our mind!!

Why Thread class’s or Runnable interface’s run() method declared not to throw checked exception??

                                                          

Before answering the above question, we need to deep dive to understand: how our implemented run() method gets invoked??

I have explained the answer in a separate post (Just to keep this post as short as possible as this is a big topic to discuss). You can check the answer in my below post.


Coming to the main point. The main requirement to throw a checked exception outside a method (to its calling method) is, the calling method must need to handle the exception thrown by the called method either by using try-catch blocks or using throws keyword.

But as discussed in the previous post (I hope you have read my previous post in the given link already. If not then please read it. Because it’s very important to understand this concept.), the run() method is getting called from JVM(Java Virtual Machine). So we cannot go and change anything in JVM to handle the exception thrown by our run() method. And that’s why the run() method is not allowed to throw any checked exception.

            

If you still try to do so, then our superhero “Mr. Compiler” has the power to stop us. The below snippet depicts how the compiler gives a compile-time error if we try to throw a checked exception from the run() method.     

 

import java.io.IOException;

public class MyThread implements Runnable{

       @Override

        public void run() throws IOException{

             // Your code goes here!!

       }

}



Conclusion

Thread’s run() method cannot throw the checked exception because there is no way to handle it from where the run() method is being called. But if you want, you can throw unchecked exceptions because there is no such requirement to handle it in the calling method.

Comments

Popular posts from this blog

Can we define explicit constructor for an anonymous inner class?

How does thread's run method get invoked??