【发布时间】: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 异常。
【问题讨论】: