This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exception treated differently Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exception treated differently" Watch "Exception treated differently" New topic
Author

Exception treated differently

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello all,
This is about Threads. The wait(), notify(), and notifyAll() method should be included inside a synchronized block/method and in try block. My question is why does it give a runtime error only when the catchint exception is 'InterruptedException'. I tried with catch block like this,
catch(Exception e) but this doesn't give a run time error. Could you please explain this for me.
Thank you very much
public class A extends Thread{
public static void main(String ar[]) {
A a = new A();
a.start();

}
public void run() {
for (int x = 0 ;x<2;x++) {

System.out.println("H");
try {
wait();
notify();
}catch(InterruptedException e ) {} // If it is Exception , it doesn't // give runtime exception
}

}
}


SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Ana Abrantes
Ranch Hand

Joined: Sep 04, 2003
Posts: 43
InterruptedException is a subclass of Exception.


Ana<p>SCJP 1.4
Narasimha Rao B.
Ranch Hand

Joined: Aug 26, 2002
Posts: 205
Hi Ransika,
Here point is, when you call wait(), notify() or notifyAll() methods from ourside of syncronized methods/blocks, compiler will throw IllegalMonitorStateException, and this exception is subclass of Exception and not checked exception.Hence,
1. When you call these methods outside the synchronized block/method, you are not getting the compile time error(Bec, IllegalMonitorStateException is not checked exception).
2. IllegalMonitorStateException is not subclass of InterruptedException, so you can't catch IllegalMonitorStateException with catch(InterruptedException) method.
3. When you use, catch(Exception e), you can very well catch the exception, IllegalMonitorStateException and can proceede with normal execution.
Hope it calrifies your doubts,
Thanks.


Narasimha
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Exception treated differently
 
Similar Threads
Exam LAb Threads Problem
K&B: Question on Threads-Selftest.
Question about wait() and notify()
Why no compilation failure
Mock exam question