• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Exception treated differently

 
Ranch Hand
Posts: 524
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
}

}
}
 
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
InterruptedException is a subclass of Exception.
 
Ranch Hand
Posts: 205
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic