Exception 类及其子类是 Throwable 的一种形式,它指出了合理的应用程序想要捕获的条件。
Exception 以及任何不同时继承自 RuntimeException 的是子类都是 checked exceptions。checked exceptions 需要在方法或者构造器中定义。
RuntimeException是任何可能被JVM运行的时候抛出的异常的超类。
RuntimeException和它的子类都是unchecked exceptions。unchecked 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?