Java Thread: Run method cannot throw checked exception

前端 未结 6 1940
名媛妹妹
名媛妹妹 2020-12-05 00:37

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 i

6条回答
  •  眼角桃花
    2020-12-05 01:16

    throws declarations are part of the methods signature. To allow checked exceptions for Runnable#run, one had to declare them on the Runnable interface and had to try/catch everytime we start a thread.

    Then again, we usually don't call the run method, we just implement it. We start() a Thread and then, somehow, the run method is called.

    But the most obvious reason: When we start threads, we usually don't want to wait until the run method terminates just to catch exceptions like this:

    try {
       new Worker().start();  // now wait until run has finished
    } catch (SomeThreadException oops) {
       // handle checked exception
    }
    

提交回复
热议问题