Java Programming - Exceptions - Discussion

Discussion Forum : Exceptions - Finding the output (Q.No. 9)
9.
What will be the output of the program?
public class MyProgram 
{
    public static void main(String args[])
    {
        try 
        {
            System.out.print("Hello world ");
        }
        finally 
        {
            System.out.println("Finally executing ");
        }
    }
}
Nothing. The program will not compile because no exceptions are specified.
Nothing. The program will not compile because no catch clauses are specified.
Hello world.
Hello world Finally executing
Answer: Option
Explanation:

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.

Discussion:
6 comments Page 1 of 1.

Reddy said:   9 years ago
Actually, no Exception has caught without catch block. So the above line is executed normally like normal program. But finally block executes independently.

Syed afaq said:   1 decade ago
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:   1 decade ago
Every catch block must have a try block. Not the other way.

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

Faisal said:   1 decade ago
If all have seen that System. Out. Print ("Hello world ") ;.

After print ln also has missed from the program.

Sam said:   9 years ago
Exactly, we can't have a try without catch block following it. So how's that even possible?

Sonali said:   1 decade ago
The program first execute try block and other execute finally block and show output.

Post your comments here:

Your comments will be displayed after verification.