Hi, This is the question I came across in one of mock exam sites.
1 Compiler error , return "Error" : statement not reached
2 Compiler error , i = 1 / 0 : Exception must be caught or declared in the throws clause
3 Compiles & prints Error when run
4 Compiles & prints Peace when run
The answer given is option 4. I did compile and run the program and it gives the same output. I didn't understand the fact that: In this case, a catch block is throwing an ArithmeticException.This exception is unhandled, then why does it not, either (1) get propogated to the caller?( method main in this case) or (2) give compile time error making the answer option 2 ? Any explainations? Thanks
[ June 27, 2004: Message edited by: Tejaswini Shirkhedkar ]
([C0DE] [/C0DE] tags added - Barry) [ June 27, 2004: Message edited by: Barry Gaunt ]
Option 4 : prints peace is correct because - Arithmetic exception is a runtime exception , so won't be caught during compile time. - finally will always be called !
Hope the explanation helps.
posted 16 years ago
Thanks a lot for your replies.. But then, in the output, it should show that java.lang.ArithmeticException etc etc etc.. But the output is just "peace" Does this mean that the ArithmeticException getting thrown in the catch block is ignored at run time? Thanks.
I think your return statement in the finally block is playing a role here. Please try replacing that with a print statement (System.out.println ("peace")). Khalid and Rasmussen's book has the following explanation on the use of transfer statements in finally block:
*** If the finally block executes a control transfer statement such as, a return or a labeled break, then this control transfer statement determines how the execution will proceed�regardless of how the try block or any catch block were executed. In particular, a value returned by a return statement in the finally block will supersede any value returned by a return statement in the try block or a catch block. ***
I wonder if this example is set to demonstrate this point.