Will catching an exception catch a parent class of that exception

后端 未结 3 507
隐瞒了意图╮
隐瞒了意图╮ 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:26

    It will only catch the Exception you specify or it's subclass. Just write it so it catches the parent Exception and you're safe.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 13:30

    Think of it as an instanceof test

    e.g.

    if (e instanceof ChildException) {
     ...
    }
    

    so specifying a class type will catch the class and its subclasses.

    0 讨论(0)
提交回复
热议问题