gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:17:49 26 4
gpt4 key购买 nike

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

我创建了三个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 并捕获 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 异常。

最佳答案

在类 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)。

关于java - 向上转换时捕获错误的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31585517/

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