Java异常try-catch异常与IOException异常 [英] Java exception try-catch Exception vs IOException

查看:435
本文介绍了Java异常try-catch异常与IOException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码编译好即使try块实际上并没有抛出任何异常。

The following code compiles ok even though the try block doesn't actually throw any Exception.

public static void main(String[] args)  {
    try {} 
    catch (Exception e) {} // compiles ok
}

但是如果catch被替换为Exception的子类,代码将无法编译。

But if the catch is replaced with a sub-class of Exception, the code won't compile.

public static void main(String[] args)  {
    try {} 
    catch (IOException e) {} // won't compile. 
}

编译器错误是:IOException的无法访问的catch块。这个异常从来没有从try语句正文中抛出。

The compiler error is: Unreachable catch block for IOException. This exception is never thrown from the try statement body.

当Exception& IOException是否被检查异常?我正在使用Java 7。

How come this behavior when both Exception & IOException are checked exceptions? I'm using Java 7.

推荐答案

编译器可以确切知道代码的哪个部分可以抛出一个 IOException ,因为它是一个被检查的异常,所以可以抛出这种异常的每个方法都必须在方法签名中指定。

The compiler can know exactly what part of the code can throw an IOException because it is a checked exception, so every method that can throw this kind of exception must specify it in the method signature.

另一方面,运行时或未选中的异常不是预期的,因为 RuntimeException (父类未经检查的异常)也扩展了类 Exception ,那么编译器就可以了。

On the other hand, runtime or unchecked exceptions are not meant to be expected, and since RuntimeException (the parent class of unchecked exceptions) also extends the class Exception, then the compiler is ok with it.

这篇关于Java异常try-catch异常与IOException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆