Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why when try won't throw a exception ,it can not compile?

 
Jianfeng Qian
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
is it because try is in the main?or because it is in the static method?
or something else?
I'm comfused.

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();
// XXX
//throw new InterruptedException();
if add the upper line ,compile failed and say that can't reach the next line.
mt2.start();
//throw new InterruptedException();
//when i add upper line,it can compile
}
catch(InterruptedException ex)
{
}
}
}
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) use code tags
2) what compiler error are you getting?
3) is this really a question related to the SCJP exam?
 
Leandro Melo
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
If you throw an exception

throw new InterruptedException();

the line below it will never be executed, that's why the compiler gives that message.
Once the exception is thrown, the program is going to the next catch (or finally) block. If there isn't one until it reaches main, your program will be halted.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic