用户工具

站点工具


开发:java:异常

定义

Exception 类及其子类是 Throwable 的一种形式,它指出了合理的应用程序想要捕获的条件。

Exception 以及任何不同时继承自 RuntimeException 的是子类都是 checked exceptionschecked exceptions 需要在方法或者构造器中定义。

RuntimeException是任何可能被JVM运行的时候抛出的异常的超类。

RuntimeException和它的子类都是unchecked exceptionsunchecked exceptions 不需要在方法或者构造器中定义。

代码

public class Test {
    public static void main(String[] s) {
        try {
            checked();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //这里不会有编译错误,但是在运行时因为没有catch会退出程序
        unchecked();
    }
 
    private static void checked() throws Exception {
        throw new Exception("checked exceptions");
    }
 
    private static void unchecked(){
        throw new RuntimeException("unchecked exceptions");
    }
}

争议

使用checked exceptions 还是 unchecked exceptions?

链接

开发/java/异常.txt · 最后更改: 2016-03-06 17:54 由 danding

粤ICP备16007019号-3