Java Programming - Exceptions - Discussion


What will be the output of the program?

public class MyProgram 
    public static void main(String args[])
            System.out.print("Hello world ");
            System.out.println("Finally executing ");

[A]. Nothing. The program will not compile because no exceptions are specified.
[B]. Nothing. The program will not compile because no catch clauses are specified.
[C]. Hello world.
[D]. Hello world Finally executing

Answer: Option D


Finally clauses are always executed. The program will first execute the try block, printing Hello world, and will then execute the finally block, printing Finally executing.

Option A, B, and C are incorrect based on the program logic described above. Remember that either a catch or a finally statement must follow a try. Since the finally is present, the catch is not required.

Syed Afaq said: (Mar 12, 2013)  
As we have learnt, it states that "every try block must have a catch block ".

Can any one please explain me about this?

Dan said: (Nov 12, 2013)  
Every catch block must have a try block. Not the other way.

'try' must have either a 'catch' and/or a 'finally'.

Faisal said: (Dec 3, 2013)  
If all have seen that System. Out. Print ("Hello world ") ;.

After print ln also has missed from the program.

Sonali said: (Dec 26, 2014)  
The program first execute try block and other execute finally block and show output.

Reddy said: (Jun 23, 2016)  
Actually, no Exception has caught without catch block. So the above line is executed normally like normal program. But finally block executes independently.

Sam said: (Aug 4, 2016)  
Exactly, we can't have a try without catch block following it. So how's that even possible?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.