Java Thread: Run method cannot throw checked exception

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

    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.

提交回复
热议问题