which ones have to be in a try block? arent they meant to be? i have seen too many codes and i have been confused if they are meant to.
Kelvin Chenhao Lim
posted 8 years ago
Here's a simple trick for the exam: the only checked exception that any of these methods throw is InterruptedException. And, as the name implies, InterruptedException occurs if this thread is prematurely interrupted while it's supposed to be "inactive" in the background. Therefore, to figure out which of these six methods throw an unchecked exception, just ask yourself which of them will put the thread into an "inactive" state.
notify() and notifyAll() clearly do not, so they're out. yield() is a little trickier, but just remember that yield() is only a suggestion to the scheduler that it should temporarily go on to process another thread... but the scheduler can return to this thread at any time, so it's never premature to interrupt a yielded thread--thus yield() doesn't throw an InterruptedException either.
The other three methods (wait(), sleep(), and join()) all force the thread to become inactive until some condition is satisfied. Thus, if the thread is then interrupted before the condition is satisfied, this would be premature and will cause an InterruptedException.
And because InterruptedException is a checked exception, you must therefore always either handle or declare the exception in your calling method. [ November 13, 2007: Message edited by: Kelvin Lim ]