方法可以在不声明的情况下抛出java.lang.Exception吗?

Java代码合法吗?显然,在不同的编译器上会得到不同的结果.

foo抛出异常而不声明它.

如果try块中的代码未声明抛出任何异常,那么我们知道到达catch块的任何Exception都是RuntimeException,因此实际上这是可以的.

但这似乎需要深入的静态代码分析,而对该方法的简单语法读取表明它是非法的.

能否请我参考语言规范的文章或部分?

public void foo() {// no  throws clause
    try {
        // Lines of code
    } catch (Exception e) {
        throw e;
    }  
}

解决方法:

查看§11.2 Compile-Time Checking of Exceptions

For each checked exception which is a possible result, the throws clause for the method or constructor must mention the class of that exception or one of the superclasses of the class of that exception (§11.2.3).

进一步的章节将详细介绍表达式和语句的异常分析.

如果您尝试使用以下代码:

    try {
        // Lines of code
    } catch (Exception e) {
        throw e;
    }

它不会有效地引发任何检查的异常.在Eclipse中,它没有给我任何编译器错误.

但是,如果尝试以下操作:

    try {
        new URL("https://www.*.com");
    } catch (Exception e) {
        throw e;
    }

它可以抛出一个检查异常,并且它(或其超类)必须在throws中提及.这使我在Eclipse中出现“未处理的异常类型MalformedURLException”编译器错误.

上一篇:JavaScript >>代表什么?


下一篇:mysql-SQL查询语法错误,使用INNER JOIN的UPDATE语句