我有以下简单的代码:
class Test {
    public static void main(String[] args) {
        Test t = new Test();
        try {
            t.throwAnotherException();
        } catch (AnotherException e) {
            t.handleException(e);
        }
        try {
            t.throwAnotherException();
        } catch (Exception e) {
            System.out.println(e.getClass().getName());
            t.handleException(e);
        }
    }
    public void throwAnotherException() throws AnotherException {
        throw new AnotherException();
    }
    public void handleException(Exception e) {
        System.out.println("Handle Exception");
    }
    public void handleException(AnotherException e) {
        System.out.println("Handle Another Exception");
    }
}
class AnotherException extends Exception {
}
为什么第二个catch中调用的方法是带签名的方法,void handleException(Exception e)而异常的类型是AnotherException?
重载方法在编译时根据形式参数类型而不是运行时类型进行解析.
这意味着,如果B extends A,你有
void thing(A x);
void thing(B x);
然后
B b = new B();
thing(b);
将寻找一个thing()需要a B,因为正式类型b是B; 但
A b = new B();
thing(b);
将寻找一个thing()需要的A,因为正式类型b是A,即使它的运行时实际类型将是B.
在你的代码,正式类型e是AnotherException在第一种情况,但是Exception在第二种情况下.AnotherException每种情况都是运行时类型.
| 归档时间: | 
 | 
| 查看次数: | 56 次 | 
| 最近记录: |