简体   繁体   中英

Why doesn't Catch Print?

try {
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted, NOT PRINTED");
}
System.out.println ("This statement is printed");

in this code sleep throws an interrupted exception and yet this doesnt print the catch statements in the output.Why?

You should read the full Javadoc for the sleep method (note the emphasis):

sleep

public static void sleep(long millis) throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.

Parameters :
millis - the length of time to sleep in milliseconds.
Throws :
InterruptedException - if any thread has interrupted the current thread . The interrupted status of the current thread is cleared when this exception is thrown.

No exception will be thrown unless the sleeping thread is actually interrupted. Here is a version of the code that more reliably tests the behavior you are examining:

Thread targetThread = new Thread() {
    @Override
    public void run() {
        try {
            Thread.sleep(5000);
            System.out.println("Target thread completed normally");
        } catch(final InterruptedException ie) {
            System.out.println("Target thread was interrupted");
        }
    }
};

targetThread.start();
targetThread.interrupt();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM