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
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.
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.
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.