有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

向上转换时捕获的java错误异常

我的问题是当向上投射时捕捉错误的异常。我不知道什么是不正确的

我创建了三个Exception,如下所示:

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和catch 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异常


共 (2) 个答案

  1. # 1 楼答案

    在类BC中,您实际上覆盖了类Af()方法的定义

    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中的重写规则)

  2. # 2 楼答案

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