Java Thread: Run method cannot throw checked exception

前端 未结 6 1939
名媛妹妹
名媛妹妹 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:13

    The reason is that exception is thrown back to the caller. Caller of run() method is not your code. It is the Thred itself. So even if run() throws exception the program cannot catch it.

    You should put thread execution result to some class level variable and then read it from there. Or alternatively use new API: executors and interface Callable that declares method call() that returns future result of the thread execution.

提交回复
热议问题