java - 捕获异常会捕获该异常的父类

标签 java exception

在 Java 中,我有一个方法捕获扩展“NewException”的异常“ChildException”。如果该方法调用另一个抛出“NewException”的方法,并且假设发生了某些事情并抛出它;捕获抛出异常的子类的调用者方法会捕获它吗?

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

那么,调用MethodThrowingNewException的异常会被MethodCatchingChildException捕获吗?

最佳答案

catch 子句将捕获与声明的异常类型赋值兼容的任何异常。在您描述的情况下,NewException 实例(不是 ChildException)不会被该 catch 子句捕获,因为您无法将 NewException 对象分配给 ChildException 变量。

规则在 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.

关于java - 捕获异常会捕获该异常的父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47618407/

相关文章:

java.util.NoSuchElementException : No line found at java. util.Scanner.nextLine(Scanner.java:1585)

java - Eclipse - 将每个主要方法分配给一个单独的控制台

Java 如何使用 Set 参数化泛型方法?

c# - 初始化 VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll) 时出现错误 80040154(类未注册异常)

c++ - 异常对象生命周期

objective-c - 为什么 NSOperation 示例代码使用 @try & @catch

python - 在 Python 中引发异常的正确方法是什么?

java - oracle中使用java进行更新和删除

java - Hibernate 内连接 ManyToOne

java - 使用sql获取平均评分