Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes try /catch problem? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "try /catch problem?" Watch "try /catch problem?" New topic
Author

try /catch problem?

sonir shah
Ranch Hand

Joined: Nov 01, 2001
Posts: 435
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

Joined: Jan 11, 2002
Posts: 203
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

Joined: Aug 26, 2001
Posts: 7610
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


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Raghav Mathur
Ranch Hand

Joined: Jan 12, 2001
Posts: 641
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 ]

Raghav.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: try /catch problem?