捕获异常会捕获该异常的父类 [英] Will catching an exception catch a parent class of that exception

查看:111
本文介绍了捕获异常会捕获该异常的父类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我有一个方法来捕获扩展'NewException'的异常'ChildException'。如果该方法调用另一个抛出'NewException'的方法,让我们说某事发生并抛出它;捕获抛出异常的子类的调用方法会捕获它吗?

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

因此,在MethodCatchingChildException中会捕获来自callingMethodThrowingNewException的异常吗?

So will the exception from callingMethodThrowingNewException get caught in MethodCatchingChildException?

推荐答案

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

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.

规则在 Java语言规范的第14.20.1节


如果由于抛出值V而突然完成try块的执行,则可以选择:

If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:


  • 如果V的运行时类型与(§5.2)try语句的任何catch子句的可捕获异常类,然后选择第一个(最左边)这样的catch子句。将值V赋给所选catch的参数子句,并执行该catch子句的块,然后有一个选择:

  • 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:


  • 如果该块正常完成,然后try语句正常完成。

  • If that block completes normally, then the try statement completes normally.

如果该块由于任何原因而突然完成,则try语句因同样的原因突然完成。

If that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

如果V的运行时类型与try语句的任何catch子句的可捕获异常类不兼容然后,由于抛出值V,try语句突然完成。

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.

这篇关于捕获异常会捕获该异常的父类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆