Java Programming - Exceptions - Discussion

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

7. 

Which statement is true?

[A]. A try statement must have at least one corresponding catch block.
[B]. Multiple catch statements can catch the same class of exception more than once.
[C]. An Error that might be thrown in a method must be declared as thrown by that method, or be handled within that method.
[D]. Except in case of VM shutdown, if a try block starts to execute, a corresponding finally block will always start to execute.

Answer: Option D

Explanation:

A is wrong. A try statement can exist without catch, but it must have a finally statement.

B is wrong. A try statement executes a block. If a value is thrown and the try statement has one or more catch clauses that can catch it, then control will be transferred to the first such catch clause. If that catch block completes normally, then the try statement completes normally.

C is wrong. Exceptions of type Error and RuntimeException do not have to be caught, only checked exceptions (java.lang.Exception) have to be caught. However, speaking of Exceptions, Exceptions do not have to be handled in the same method as the throw statement. They can be passed to another method.

If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

  1. An exception arising in the finally block itself.
  2. The death of the thread.
  3. The use of System.exit()
  4. Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.


Dipali said: (Jun 14, 2015)  
I think finally is not compulsory after try block. There should always be a catch block.

Dablu Gupta said: (Jul 26, 2015)  
Try block is not mandatory to have catch block, it can have either catch or finally block subsequently.

Rick said: (Feb 22, 2016)  
Perhaps reword the [D].

Implies to me that the finally block will begin executing at the same time as the try block which is not the case. Caught me out ;-).

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.