• [转]Unchecked Exception 和 Checked Exception 比较


    Throwable类是所有异常的始祖,它有两个直接子类Error / Exception: 
      Error仅在Java虚拟机中发生动态连接失败或其它的定位失败的时候抛出一个Error对象。一般程序不用捕捉或抛出Error对象。 

    Unchecked Exception: 
    a. 指的是程序的瑕疵或逻辑错误,并且在运行时无法恢复。 
    b. 包括Error与RuntimeException及其子类,如:OutOfMemoryError, UndeclaredThrowableException, IllegalArgumentException, IllegalMonitorStateException, NullPointerException, IllegalStateException, IndexOutOfBoundsException等。 
    c. 语法上不需要声明抛出异常。 

    Checked Exception: 
    a. 代表程序不能直接控制的无效外界情况(如用户输入,数据库问题,网络异常,文件丢失等) 
    b. 除了Error和RuntimeException及其子类之外,如:ClassNotFoundException, NamingException, ServletException, SQLException, IOException等。 
    c. 需要try catch处理或throws声明抛出异常。 

    有点困惑的是:RuntimeException (Unchecked)是Exception (Checked)的子类。 

    示例:

    1 public class GenericException extends Exception {
    2     public GenericException() {
    3     }
    4 
    5     public GenericException(String message) {
    6         super(message);
    7     }
    8 }
     1 public class TestException {
     2     public void first() throws GenericException {
     3         throw new GenericException("Generic exception"); // Checked Exception需要显式声明抛出异常或者try catch处理
     4     }
     5     
     6     public void second(String msg) {
     7         if (msg == null)
     8             throw new NullPointerException("Msg is null"); // Unchecked Exception语法上不需要处理
     9     }
    10     
    11     public void third() throws GenericException {
    12         first(); // 调用有Checked Exception抛出的方法也需要try catch或声明抛出异常
    13     }
    14 
    15     public static void main(String[] args) {
    16         TestException test = new TestException();
    17         try {
    18             test.first();
    19         } catch (GenericException e) {
    20             e.printStackTrace();
    21         }
    22         
    23         test.second(null);
    24     }
    25 }
  • 相关阅读:
    java web的安全约束--表单的验证
    Java web的安全约束--Basic验证
    setExecuteExistingDelayedTasksAfterShutdownPolicy方法与setContinueExistingPeriodicTasksAfterShutdownPolicy方法的比较
    关于scheduleAtFixedRate方法与scheduleWithFixedDelay的使用
    ExecutorService的invokeAny方法
    CompletionService的异常处理
    CompletionService的poll方法
    include指令
    向jsp页面传值时出现乱码
    new home page
  • 原文地址:https://www.cnblogs.com/jasonzeng888/p/5633852.html
Copyright © 2020-2023  润新知