捕获的异常没有使用正确的方法处理。

3
我有以下简单的代码:

我有以下简单的代码:

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

我没有完全理解你的问题,但我感觉你把方法名和异常名混淆了。 - Sid
4个回答

6

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

这意味着如果B extends A,并且您有

void thing(A x);

void thing(B x);

那么

B b = new B();
thing(b);

将寻找一个接受Bthing(),因为形参b的类型是B;但是

A b = new B();
thing(b);

将查找一个接受 A 参数的 thing(),因为 b 的形式类型是 A,尽管它的运行时实际类型是 B

在您的代码中,第一种情况下 e 的形式类型为 AnotherException,而第二种情况下为 Exception。每种情况下的运行时类型都是 AnotherException


0

我猜你想测试哪个Exception会被捕获,对吧?

那么修改你的代码,只抛出一个Exception

    try {
        t.throwAnotherException();
    } catch (AnotherException e) {
        t.handleException(e);
    }
    catch (Exception e) {
        System.out.println(e.getClass().getName());
        t.handleException(e);
    }

这个程序按预期工作。


0

Exception是超类,所以如果你在catch子句中首先写上(Exception e),它将始终被满足并执行。

为了改进你的代码,你可以按照下面的方式修改你的代码。

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 (AnotherException e) {
            t.handleException(e);
        }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 {

}

0

AnotherException继承自Exception,这意味着无论何处使用“Exception”,使用“AnotherException”的实例都将符合条件。

您可能应该阅读有关扩展类的更详细解释,因为它在编程中非常重要。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接