【问题标题】:Wrong Exception catched when up-casting向上转换时捕获到错误的异常
【发布时间】:2015-07-23 11:04:16
【问题描述】:

我的问题是向上转换时错误捕获的异常。我不知道什么是不正确的......

我创建了三个Exceptions,看起来像这样:

class A extends Exception{
    public void f() throws A{
        System.out.println("Exception from A()");
        throw new A();
    }
    public void g() throws A{
        System.out.println("Exception from A()");
        throw new A();
    }
}
class B extends A{
    @Override
    public void f() throws B{
        System.out.println("Exception from B()");
        throw new B();
    }
}
class C extends B{
    @Override
    public void f() throws C{
        System.out.println("Exception from C()");
        throw new C();
    }
}

...我想创建C 对象并将此对象转换为A 并捕获A 异常。我的主要看起来像这样:

public static void main(String[] args) {
        try {
            C obj = new C();
            ((A)obj).f(); // cast object C --> A....  Why it isn't work ?!
                            // should catch exception A not C !!!
                            // problem is when f() method is overrided by subclass

//            ((A)obj).g(); // working CORRECT when use other method...

//           A obj2 = (A) obj; // I try other casting type
//           obj2.g(); //method g() from exception A - work CORRECT, exception A catched...

        } catch (C e) { //third in hierarchy
            e.printStackTrace(System.err);
        } catch (B e) { //second..
            e.printStackTrace(System.err);
        } catch (A e) { //base
            e.printStackTrace(System.err);
        }
    }

在输出处 netbeans 返回信息:

Exception from C()
exceptions.C
    at exceptions.C.f(HierarchyExceptions.java:24)
    at exceptions.HierarchyExceptions.main(HierarchyExceptions.java:32)
BUILD SUCCESSFUL (total time: 0 seconds)

我不知道为什么它返回错误的异常...我尝试评论

            //} catch (C e) { //third in hierarchy
            //    e.printStackTrace(System.err);
            //} catch (B e) { //second..
            //    e.printStackTrace(System.err);
            } catch (A e) { //base
                e.printStackTrace(System.err);
            }

...但它也返回 C 异常。

【问题讨论】:

    标签: java exception


    【解决方案1】:

    BC 类中,您实际上覆盖了A 类中f() 方法的定义。

    C obj = new C();
    ((A)obj).f(); // cast object C --> A....  Why it isn't work ?!
                  // should catch exception A not C !!!
                  // problem is when f() method is overrided by subclass
    

    此代码将创建类C 的实例并将其存储到类型为A 的局部变量中。一旦你调用了f() 方法,它将在C 的真实实例上执行,而不是A(Java 中的覆盖规则)。

    【讨论】:

    • 重写 f() 方法是有意的,但是当我向上转换时,我应该从转换对象而不是之前创建引用的对象中获得异常......
    • 所以不可能通过向上转换来使用 A 超类的异常吗? NetBeans 向我展示了我使用 A 中的 f() 方法,所以我很惊讶,NetBeans 告诉我这个(看屏幕截图)dropbox.com/s/9vzrops8cqwvaif/…
    • 哇哦,现在我明白了! :) 我认为可以调用被覆盖的方法(来自超类的方法)谢谢回答! ;)
    【解决方案2】:

    这是正确的行为,无论是否调用正确的实现:这是Dynamic method dispatch的概念

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 2015-06-11
      • 1970-01-01
      • 2014-03-21
      • 2020-05-30
      • 2023-01-28
      • 1970-01-01
      • 1970-01-01
      • 2010-12-14
      相关资源
      最近更新 更多