Exceptions

Q1: What will be the output of the program?
public class Test 
{  
    public static void aMethod() throws Exception 
    {
        try /* Line 5 */
        {
            throw new Exception(); /* Line 7 */
        } 
        finally /* Line 9 */
        {
            System.out.print('finally '); /* Line 11 */
        } 
    } 
    public static void main(String args[]) 
    {
        try 
        {
            aMethod();  
        } 
        catch (Exception e) /* Line 20 */
        {
            System.out.print('exception '); 
        } 
        System.out.print('finished'); /* Line 24 */
    } 
}

A finally

B exception finished

C finally exception finished

D Compilation fails

ANS:A - finally

This is what happens:(1) The execution of the try block (line 5) completes abruptly because of the throw statement (line 7). (2) The exception cannot be assigned to the parameter of any catch clause of the try statement therefore the finally block is executed (line 9) and 'finally' is output (line 11). (3) The finally block completes normally, and then the try statement completes abruptly because of the throw statement (line 7). (4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20). This prints 'exception'. (5) Lastly program execution continues, because the exception has been caught, and 'finished' is output (line 24).



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.