| Author |
exception is never thrown in try compiler error
|
catherine powell
Greenhorn
Joined: Oct 07, 2006
Posts: 26
|
|
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
Joined: Aug 02, 2006
Posts: 109
|
|
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
Joined: Oct 07, 2006
Posts: 26
|
|
|
I understand now. Thanks very much again for your help.
|
 |
 |
|
|
subject: exception is never thrown in try compiler error
|
|
|