Java Thread: Run method cannot throw checked exception

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

    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?
    

提交回复
热议问题