简体   繁体   中英

Will catching an exception catch a parent class of that exception

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 say something happens and throws it; will the caller method that catches a child class of the exception thrown catch it?

public MethodCatchingChildException
{
  try
  {
     //stuff
     callingMethodThrowingNewException();
     //stuff
  }
  catch (ChildException e)
  {
     //stuff
  }
}

So will the exception from callingMethodThrowingNewException get caught in MethodCatchingChildException?

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

eg

if (e instanceof ChildException) {
 ...
}

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM