my dog learned polymorphism*
The moose likes Beginning Java and the fly likes Why did the code throw an Error? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why did the code throw an Error?" Watch "Why did the code throw an Error?" New topic
Author

Why did the code throw an Error?

henry joe
Ranch Hand

Joined: Jul 24, 2012
Posts: 32
Hello guys,

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

BalaMurali dhar
Ranch Hand

Joined: Apr 14, 2012
Posts: 60
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

Joined: Jun 02, 2012
Posts: 186
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

Joined: Apr 04, 2012
Posts: 924
    
    1

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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why did the code throw an Error?