Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why did the code throw an Error?

 
henry joe
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello guys,

I was just wondering why this piece of code will throw an Error.

 
BalaMurali dhar
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code is like that
class Salmon extends Thread
{
public static long id;
public void run()
{
for(int i = 0;i<4; i++){
//if(i==2&& id ==Thread.currentThread().getId()){
if(i==2){
new Thread(new Salmon()).start();
throw new Error();
}
System.out.println(i + " ");
}
}
public static void main(String[] args)
{
Thread t1 = new Thread();
id = t1.getId();
t1.start();
}
}
 
Gaurangkumar Khalasi
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
henry joe wrote:I was just wondering why this piece of code will throw an Error.

Because of

Thread "t1" created at line no. 17 will execute the run() method;Because of t1.start();. Now in run method, there is for loop and in it for i==2 you will create a new thread and called up start() to execute its run method (So, currently there are two runnable threads). After creation of it there is an explicit throw sentence. So t1 will be terminated with Error. But a new thread is alive their, which will again create a new one and throw an error. So, you will get infinite results of Errors and 0 1...
 
gurpeet singh
Ranch Hand
Posts: 924
1
Fedora Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
henry joe wrote:Hello guys,

I was just wondering why this piece of code will throw an Error.



it will throw a Error because you yourself are throwing Error. or you can say it is a programatically thrown Error(i doubt the terminology programatically and jvm thrown). Rest Gaurang has explained beautifully
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic