使用正确的方法无法处理捕获的异常

che*_*1k4 3 java exception

我有以下简单的代码:

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 {

}
Run Code Online (Sandbox Code Playgroud)

为什么第二个catch中调用的方法是带签名的方法,void handleException(Exception e)而异常的类型是AnotherException

chi*_*ity 6

重载方法在编译时根据形式参数类型而不是运行时类型进行解析.

这意味着,如果B extends A,你有

void thing(A x);

void thing(B x);
Run Code Online (Sandbox Code Playgroud)

然后

B b = new B();
thing(b);
Run Code Online (Sandbox Code Playgroud)

将寻找一个thing()需要a B,因为正式类型bB; 但

A b = new B();
thing(b);
Run Code Online (Sandbox Code Playgroud)

将寻找一个thing()需要的A,因为正式类型bA,即使它的运行时实际类型将是B.

在你的代码,正式类型eAnotherException在第一种情况,但是Exception在第二种情况下.AnotherException每种情况都是运行时类型.