go to previous page   go to home page   go to next page

Answer:

Yes.


How try and catch Work

How try and catch work

Here is how try and catch work:

  1. When an Exception is thrown by a statement in the try block, the catch blocks are examined one-by-one starting starting with the first.
  2. The first catch block to match the type of the Exception gets control.
    • In the diagram, X, Y, and Z represent different classes of exceptions.
    • For example, Y might be IOException.
    • A catch block matches exceptions of the named class and all subclasses
    • If Y is IOException, it also matches FileNotFoundException, a subclass.
  3. Only one catch block gets control.
  4. If no catch block matches the Exception, none is picked, and execution leaves this method (just as if there were no try block.)
  5. The most specific Exception classes should appear first in the structure, followed by the more general Exception classes.
    • If the general class came first, it would be the first match for all its subclasses.
  6. The statements in the chosen catch block execute sequentially. After the last statement executes, control goes to the first statement that follows the try/catch structure.
    • (A finally block can be added to the structure, which will always be executed.)
    • (This explained below.)
  7. Control does not return to the try block.

QUESTION 7:

Must the catch blocks list all possible Exceptions?


go to previous page   go to home page   go to next page