Java Thread: Run method cannot throw checked exception

前端 未结 6 1937
名媛妹妹
名媛妹妹 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 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?
    
    0 讨论(0)
  • 2020-12-05 01:27

    Suppose thread A starts up thread B. Then thread B throws an exception. You might think it would be nice for thread A to catch it. But where? By the time thread B thows the exception, who knows what thread A is doing? To take a trivial example, suppose we have this code in thread A:

    try
    {
      threadB=new PurgeAbandonedCarts();
      threadB.start();
    }
    catch (NullPointerException panic)
    {
      ... handle errors purging abandoned carts ...
    }
    try
    {
      processNewOrders();
    }
    catch (NullPointerException panic)
    {
      ... handle problems in new orders ...
    }
    finally
    {
      ... clean up ...
    }
    

    So we start up thread B to purge abandoned carts. Once it gets starte, we move on to processing new orders. Then thread B throws a null pointer exception. Should it be caught by the catch block associated with thread B, or the one associated with processing new orders?

    If it goes to the new orders catch, it's likely that any code here has nothing to do with cleaning up problems with thread B. That can't be the right answer.

    If you say the one associated with thread B, then that means that during the processing of new orders, control could suddenly be yanked out and sent back to try thread B catch block. But then what happenned to processing new orders? Do we just stop in the middle? Do we not even hit the finally block? And when we're done, do we then just keep executing and fall through to processing new orders again? Do we process orders twice? This can't be the right answer either.

    Thus, there is nowhere to go if run throws an exception. The only logical thing to do is to have the run method catch any exceptions thrown itself, and handle them within the new thread.

    0 讨论(0)
  • 2020-12-05 01:27

    The more obvious solution to the previous answers is that if you throw a checked exception, you are not correctly implementing run() as specified in the runnable interface.

    It won't even compile:

    run() in TestClass cannot implement run() in java.lang.Runnable; 
    overridden method does not throw java.lang.Exception  
    
    0 讨论(0)
提交回复
热议问题