Java OCA OCP Practice Question 615

Question

If an exception matches two or more catch blocks, which catch block is executed?

  • A. The first one that matches is executed.
  • B. The last one that matches is executed.
  • C. All matched blocks are executed.
  • D. It is not possible to write code like this.


A.

Note

If an exception matches multiple catch blocks, the first one that it encounters will be the only one executed.

Option A is correct, and Options B and C are incorrect.

Option D is incorrect.

It is possible to write two consecutive catch blocks that can catch the same exception, with the first type being a subclass of the second.

In this scenario, an exception thrown of the first type would match both catch blocks, but only the first catch block would be executed, since it is the more specific match.




PreviousNext

Related