File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception treated differently

 
Ransika deSilva
Ranch Hand
Posts: 524
  • 0
  • Mark post as helpful
  • send pies
  • 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
}

}
}
 
Ana Abrantes
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
InterruptedException is a subclass of Exception.
 
Narasimha Rao B.
Ranch Hand
Posts: 205
  • 0
  • Mark post as helpful
  • send pies
  • 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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic