Will catching an exception catch a parent class of that exception

后端 未结 3 528
隐瞒了意图╮
隐瞒了意图╮ 2021-01-14 12:40

In Java I have a method catching an exception \'ChildException\' that extends \'NewException\'. If that method calls another method that throws a \'NewException\' and let\'s

3条回答
  •  不知归路
    2021-01-14 13:28

    A catch clause will catch any exception that is assignment-compatible with the declared type of the exception. In the case you describe, an instance of NewException (that is not a ChildException will not be caught by that catch clause because you cannot assign a NewException object to a ChildException variable.

    The rules are spelled out in section 14.20.1 of the Java Language Specification:

    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:

    • If the run-time type of V is assignment compatible with (§5.2) a catchable exception class of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed, and then there is a choice:

      • If that block completes normally, then the try statement completes normally.

      • If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

    • If the run-time type of V is not assignment compatible with a catchable exception class of any catch clause of the try statement, then the try statement completes abruptly because of a throw of the value V.

提交回复
热议问题