Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception is never thrown in try compiler error

 
catherine powell
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,

I am a little confused as to the rule regarding when the compiler will complain that an exception is not thrown in the body of a try block. The following code compiles without a problem:

public class ThrowTest{
public static void main(String[] args){
try{}
catch(Exception e){}
}
}

However, the following code will not compile because...
MyThread.java:19: exception java.lang.InterruptedException is never thrown in body of corresponding try statement
}catch(InterruptedException ex){}
^

public class MyThread extends Thread{

String myName;

MyThread(String name){myName=name;}

public void run(){
for(int i=0;i<100;i++){
System.out.println(myName);
}
}

public static void main(String[] args){
try{
MyThread mt1 = new MyThread("mt1");
MyThread mt2 = new MyThread("mt2");
mt1.start();
mt2.start();
}catch(InterruptedException ex){}
}

}

Could someone please explain what the rule is regarding this type of compiler error? Thanks very much in advance.
 
Chetan Raju
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you write catch(Exception e) this is applicable for all exceptions including runtime exceptions. Since runtime exceptions are unchecked exceptions the compiler doesn't complain.

However, InterruptedException is a Checked exception and the compiler checks to see that there is a possibility of this exception thrown in try clause.
 
catherine powell
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand now. Thanks very much again for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic