java - Why do I need to handle an exception for Thread.sleep()? -



java - Why do I need to handle an exception for Thread.sleep()? -

to code compile, can either:

put phone call thread.sleep() in try/catch block, or have printall() declare can throw interruptedexception.

why have this?

class test { public static void main( string[] args ) { printall( args ); } public static void printall( string[] line ) { system.out.println( lines[ ] ); thread.currentthread().sleep( 1000 ): } }

(sample code kathy sierra's scjp book.)

i know exception thread.sleep() throws checked exception, have handle it, in situation thread.sleep() need throw exception?

if method declared in way can throw checked exceptions (exceptions not subclasses of runtimeexception), code calls must phone call in try-catch block or caller method must declare throw it.

thread.sleep() declared this:

public static void sleep(long millis) throws interruptedexception;

it may throw interruptedexception straight extends java.lang.exception have grab or declare throw it.

and why thread.sleep() declared way? because if thread sleeping, thread may interrupted e.g. thread.interrupt() thread in case sleeping thread (the sleep() method) throw instance of interruptedexception.

example:

thread t = new thread() { @override public void run() { seek { system.out.println("sleeping..."); thread.sleep(10000); system.out.println("done sleeping, no interrupt."); } grab (interruptedexception e) { system.out.println("i interrupted!"); e.printstacktrace(); } } }; t.start(); // start thread: t t.interrupt(); // main thread interrupts t, thread.sleep() phone call // within t's run() method throw interruptedexception!

output:

sleeping... interrupted! java.lang.interruptedexception: sleep interrupted @ java.lang.thread.sleep(native method) @ main$1.run(main.java:13)

java multithreading exception

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -