0

我有这两个java代码:

class test {
    public static void main(String[] args) throws IOException {
        System.out.println("Before try”");
        try{}
        catch(Throwable d ) {}
        System.out.println("done");
    }
}

它将在尝试完成之前编译和打印。

class test {
    public static void main(String[] args) throws IOException {
        System.out.println("Before try”");
        try{}
        catch(java.io.IOException e ) {}
            System.out.println("done");
        }
    }
}

这将导致编译错误:

exception java.io.IOException is never thrown in body of corresponding 
try statement
    at javaapplication8.test.main(Try.java:63) 

可抛出异常和 IOException 有什么区别才能得到这些结果,是否有规则知道需要抛出哪个异常?

4

2 回答 2

1

Java 有一个检查异常的概念。检查所有 Throwable 除非它们ErrorRuntimeException

在 catch 类中,编译器可以确定您是否可以抛出已检查的异常(在正常情况下),但它无法判断您是否抛出了未经检查的异常,因此如果您捕获任何未经检查的异常或父级,它无法确定您是否可以扔掉它。

于 2015-01-27T21:14:44.423 回答
0

您的 promise 声明main它可以抛出一个IOException,但是您的代码违反了该承诺(因为您自己抓住了它)。

于 2015-01-27T21:14:19.143 回答