To get this code to compile, I can either:
Thread.sleep()
in a try/catch block, orprintAll()
declare that it can throw an InterruptedException
.Why do I have to do this?
class Test {
public static void main( String[] args ) {
printAll( args );
}
public static void printAll( String[] line ) {
System.out.println( lines[ i ] );
Thread.currentThread().sleep( 1000 ):
}
}
(Sample code from Kathy Sierra's SCJP book.)
I know that the exception which Thread.sleep()
throws is a checked exception, so I have to handle it, but in what situation does Thread.sleep()
need to throw this exception?
If a method is declared in a way that it can throw checked exceptions (Exception
s that are not subclasses of RuntimeException
), the code that calls it must call it in a try-catch
block or the caller method must declare to throw it.
Thread.sleep()
is declared like this:
public static void sleep(long millis) throws InterruptedException;
It may throw InterruptedException
which directly extends java.lang.Exception
so you have to catch it or declare to throw it.
And why is Thread.sleep()
declared this way? Because if a Thread
is sleeping, the thread may be interrupted e.g. with Thread.interrupt()
by another thread in which case the sleeping thread (the sleep()
method) will throw an instance of this InterruptedException
.
Example:
Thread t = new Thread() {
@Override
public void run() {
try {
System.out.println("Sleeping...");
Thread.sleep(10000);
System.out.println("Done sleeping, no interrupt.");
} catch (InterruptedException e) {
System.out.println("I was interrupted!");
e.printStackTrace();
}
}
};
t.start(); // Start another thread: t
t.interrupt(); // Main thread interrupts t, so the Thread.sleep() call
// inside t's run() method will throw an InterruptedException!
Output:
Sleeping...
I was interrupted!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at Main$1.run(Main.java:13)