gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:53 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com