Java 编译时检查异常

标签 java exception checked-exceptions

ExceptionIOException 都是编译时检查的异常。

但是,我们不能在 catch block 中使用 IOException。但是我们可以在 catch block 中使用 Exception 是什么原因。

    import java.io.*;
    class Demo{
        public static void main(String args[]){
            try{

            }catch(IOException e){ // Does not compile

            }

            try{

            }catch(Exception e){ // Compile

            }
        }
    }

最佳答案

除了 Exception(或 Throwable)之外,您无法捕获从未在 try block 中抛出的已检查异常。此行为由 JLS, Section 11.2.3 指定:

It is a compile-time error if a catch clause can catch checked exception class E1 and it is not the case that the try block corresponding to the catch clause can throw a checked exception class that is a subclass or superclass of E1, unless E1 is Exception or a superclass of Exception.

关于Java 编译时检查异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32463601/

相关文章:

java - JLS 的哪些部分证明能够像未经检查一样抛出已检查异常?

java - 如何在 Mockito 中多次 stub 异常

java - NoUniqueBeanDefinitionException : no qualifying bean of type. 我定义了一个匹配的 bean,但我发现了 2 个

java - 重载库类构造函数

c# - 实现返回任务的方法时的契约(Contract)约定

java - 创建一个方法来检查不同的对象,如果 null 抛出异常

java - 在不同的 JUnit 测试中管理已检查的异常

java - 如何判断异常是检查还是不检查?

java - 我应该如何解决 DI 和测试的上下文对象?

java - 查找 3 个数字中第二小的