This week's book giveaway is in the Design forum.
We're giving away four copies of Design for the Mind and have Victor S. Yocco on-line!
See this thread for details.
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

wizlab mock question

 
Shashank Sharma
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




this code should right away give error when throwing ex in inner catch block exception not handeled.
how does above code prints catchfinally1finally2 .it goes fine when i un comment line 1
 
Milan Sutaria
Ranch Hand
Posts: 122
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i find no problem. can you explain further why should it give error?
 
Tom Gustafsson
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"
this code should right away give error when throwing ex in inner catch block exception not handeled.
how does above code prints catchfinally1finally2 .it goes fine when i un comment line 1
"

I am not sure whether I understood the question, but it goes to finally block before throwing the exception. If you have the exit uncommented, it won't throw exception because it exits execution before throwing.

try {
throw new RuntimeException();
}finally {
System.out.println("Finally");
}

That one also prints finally before throwing exception.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


First of all the code will not give any compilation error as you have declared Exception in the throws clause of the main method.

Now lets go through the execution of the program...

The exception thrown at (1) is caught at (2).

another exception is thrown at (3) which is again caught at (4)

Line (5) is executed and "Catch" is displayed.

Another exception is thrown at (6) which is not caught.

As you know finally is always executed whether try or any catch trows any exception or run successfully or return any value.
So the finally associated with try(2) is executed. Here Finally1 is displayed at (7) so total "CatchFinally1" has been displayed till now.

Now the finally associated with try(1) is executed which displays Finally2 at (8).
So "CatchFinally1Finally2" is displayed at the end.

Now if you comment line (9) then Exception is thrown.
If you uncomment line (9) then the program exits without throwing any exception.
 
Shashank Sharma
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic