JAVA问题:在相应的 try 语句主体中不能抛出异常错误

来源:互联网 发布:什么是网络专供 编辑:程序博客网 时间:2024/05/20 00:49
        try{            InputStream in = new FileInputStream("111.txt");        }        catch(FileNotFoundException | UnknownHostException ex)        {            System.out.println(ex.getClass().getName());        }

在执行上述代码时,会报错:

Error:(147, 9) java: 在相应的 try 语句主体中不能抛出异常错误java.net.UnknownHostException

而以下代码可通过编译:

            try{                InputStream in = new FileInputStream("111.txt");            }            catch(FileNotFoundException | ArrayIndexOutOfBoundsException ex)            {                System.out.println(ex.getClass().getName());            }

这是因为ArrayIndexOutOfBoundsException异常是RuntimeException的子类,而UnknownHostException是IOException的子类,前者在编译时会被忽略,而后者在编译时编译器会检查try代码块中是否抛出了相应的异常,因此报错。

6 0
原创粉丝点击