• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why did the code throw an Error?

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello guys,

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

 
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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();
}
}
 
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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...
 
Ranch Hand
Posts: 924
1
Netbeans IDE Fedora Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic