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

try /catch problem?

 
sonir shah
Ranch Hand
Posts: 435
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which digits, and in which order, will be printed when the following program is run?

Ans : It will print 1,4,5
I feel that it will print 1,2 and 4 because when 5 is divided by 0, ArithmeticException is caught in the catch block.As there is not 'return' after the first catch, it will pass on the statement to second catch,which will print 2.After that there is a return statement, which will lead to the finally statement which will print 4
Please help
Sonir
 
Shivaji Marathe
Ranch Hand
Posts: 203
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sonir :
Remember that only one catch block will process the exception. So the first catch block that matches the Arithmatic exception will process it and then the control will pass to the finally.
In fact, if you declared the catch block of the runtime exception befor the catch block of the arithmatic exception the compiler will complain.
and display a message "catch not reached.
catch (ArithmeticException e){ "
If you want the exception to be caught by the subsequent catch blocks , you have to rethrow it at the end of the first catch block.
Hope this helps
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no the answer is correct since only one catch blocm will execute depending on the Exception that is throwm. In this case 5/0 will raise an ArithmeticException. The first catch block will execute and then the control is transferred to the finally block and then it goes on. Bottom line is only one catch block is executed that's why you have to organize the catch block in a consistent way, that is, from the most specific to the less specific...
HIH
 
Raghav Mathur
Ranch Hand
Posts: 641
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And had it not thrown any exceptions , it would have printed just 4 ( the finally block ).

Ans : It will print 1,4,5
I feel that it will print 1,2 and 4 because when 5 is divided by 0, ArithmeticException is caught in the catch block.As there is not 'return' after the first catch, it will pass on the statement to second catch,which will print 2.After that there is a return statement, which will lead to the finally statement which will print 4
Please help
Sonir[/qb]<hr></blockquote>
[ January 17, 2002: Message edited by: raghav mathur ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic