Java Programming - Exceptions - Discussion


What will be the output of the program?

public class RTExcept 
    public static void throwit () 
        System.out.print("throwit ");
        throw new RuntimeException();
    public static void main(String [] args) 
            System.out.print("hello ");
        catch (Exception re ) 
            System.out.print("caught ");
            System.out.print("finally ");
        System.out.println("after ");

[A]. hello throwit caught
[B]. Compilation fails
[C]. hello throwit RuntimeException caught after
[D]. hello throwit caught finally after

Answer: Option D


The main() method properly catches and handles the RuntimeException in the catch block, finally runs (as it always does), and then the code returns to normal.

A, B and C are incorrect based on the program logic described above. Remember that properly handled exceptions do not cause the program to stop executing.

Mudit said: (Mar 8, 2013)  
Since RuntimeException is not a subclass of Exception class and neither it needs to be declared or handle then how can a catch clause with Exception object as argument can handle this Runtime Exception?

Azam said: (Mar 31, 2014)  
Sorry, but RuntimeException class is the Parent class of Exception class. So it can be handled by exception class.

Anurag Singh said: (Oct 2, 2014)  
Hi, Exception class is parent class of RunTimeException.

Prasad said: (Feb 24, 2015)  
I have a question on above code. I think the static method need to be execute first.

Sree said: (Aug 6, 2015)  
If we have normal static method and public static void main() method, First preference is given to static main method.

Wojtek said: (Sep 16, 2015)  
Why we do not need to statement 'throws' RuntTimeEx?

Seonab said: (Mar 8, 2017)  
Class is the Parent class of Exception class.

Seonab said: (Mar 8, 2017)  
I have a question on above code. I think the static method need to be execute first.

Nikshitha said: (Sep 16, 2018)  
But after finally block, if any statement exists does it executes?

As per my knowledge, I think it should not execute.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.