【问题标题】:How does Exception class know about the ArithmeticException class?Exception 类如何知道 ArithmeticException 类?
【发布时间】:2017-07-25 02:38:51
【问题描述】:

我读过超类对象可以指向子类对象但不知道子类的内容。 那么超类如何才能捕获子类类型的异常呢?

我在这里很困惑。请有人帮忙

class abc {
    public static void main(String k[]) {
        try {
            int a = 0;
            int b = 56 / 0;
        } catch (Exception e) {
            System.out.println(" divide by zero ");
        }

    }
}

【问题讨论】:

    标签: java subclass superclass


    【解决方案1】:

    超类不知道它的子类。反之亦然,即子类知道它是直接超类。

    您的catch 语句有点像带有instanceof 运算符的if 语句:

    if (thrownException instanceof Exception) {
        Exception e = (Exception) thrownException;
        System.out.pritnln("divide by zero");
    }
    

    instanceof 运算符在逻辑上是通过获取左侧对象的类并检查它或它的任何超类是否是运算符右侧的类来完成的。

    所以,如您所见,不是Exception 知道ArithmeticException,而是ArithmeticException 知道Exception,以便catch 语句起作用。

    【讨论】:

      【解决方案2】:

      这是两个独立的东西。 第一种情况是泛型类型不具有特定类型的可见性。第二种是反向的,其中异常与特定类型匹配,如果未找到,则沿类层次结构查找下一个泛型类型,并找到下一个直到匹配。

      在这个特定场景中,AE 是 E 的子类,因此如果您没有 AE,它会匹配层次结构中的下一个泛型类型,即异常

      【讨论】:

        【解决方案3】:

        ArithmeticExceptionException 的子类型。因此,在您的catch 中,您所说的是“捕获所有ExceptionException 的子类型。在这种情况下,包括ArithmeticException

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-15
          • 1970-01-01
          • 2012-03-09
          • 1970-01-01
          相关资源
          最近更新 更多