Java Programming - Exceptions - Discussion

Discussion :: Exceptions - Pointing out the correct statements (Q.No.4)


System.out.print("Start ");
    System.out.print("Hello world");
    throw new FileNotFoundException();
System.out.print(" Catch Here "); /* Line 7 */
catch(EOFException e) 
    System.out.print("End of file exception");
catch(FileNotFoundException e) 
    System.out.print("File not found");
and given that EOFException and FileNotFoundException are both subclasses of IOException, and further assuming this block of code is placed into a class, which statement is most true concerning this code?

[A]. The code will not compile.
[B]. Code output: Start Hello world File Not Found.
[C]. Code output: Start Hello world End of file exception.
[D]. Code output: Start Hello world Catch Here File not found.

Answer: Option A


Line 7 will cause a compiler error. The only legal statements after try blocks are either catch or finally statements.

Option B, C, and D are incorrect based on the program logic described above. If line 7 was removed, the code would compile and the correct answer would be Option B.

Nagendra said: (Dec 20, 2011)  
Yes, After try block the legal statement is catch or finally. !

Tiago said: (Jan 18, 2012)  
The first catch block will also cause compiler error. Because it will never be executed.

Mayuri said: (Oct 1, 2012)  
The first catch block causes compiler error as we are throwing FileNotFoundException it will not catch EOFException.

Kalman said: (Nov 17, 2015)  
"Assuming this block of code is placed into a class".

Indeed it must be placed into a method to work.

Groumpf said: (Dec 4, 2015)  
I agree with Kalman.

"Assuming this block of code is placed into a class" is confusing.

I answered compilation error because this block cannot be put in a class.

Prabhat Mishra said: (Dec 20, 2016)  
Please give the detailed answer.

Tohid said: (Jan 16, 2017)  
Can we use throw in try block?

Ranjeet said: (Jan 27, 2018)  
I didn't get exact it. Please explain me.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.