Java Exception和Error的差別

來源:互聯網
上載者:User

標籤:基類   str   parent   err   運行   memory   方法   dcl   ica   

Java中異常的抽象類別是Throwable,在此基礎上。派生出兩大類:Error和Exception。

Error是程式中的嚴重錯誤,不應該用try…catch包括。Javadoc的說明例如以下:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

常見的Error有:AssertionError、OutOfMemoryError、StackOverflowError。

Exception分兩類:Checked Exception和Unchecked Exception。
Unchecked Exception的基類是RuntimeException。全部繼承自RuntimeException的Exception都屬於Unchecked Exception, 如:NullPointerException、ArrayIndexOutOfBoundsException。
Checked Exception直接繼承自Exception,全部不繼承RuntimeException的Exception都屬於Checked Exception,如:FileNotFoundException。

Checked Exception和Unchecked Exception都能夠用try…catch包括。當中,Checked Exception在編譯時間檢查是否有想要的catch處理,因此必要有try…catch包括,或者方法簽名處拋出相應的異常。而Unchecked Exception在運行時推斷,所以不一定要try…catch包括。並且,Unchecked Exception往往是程式本身存在bug,一般不catch這種錯誤。

備忘1:
在try中運行return語句,依舊會運行finally語句塊。除非在try語句中結束JVM進程(system.exit(0))

public class Hello{    public static void main(String[] args){        try{            System.out.println("in try");            return;        }catch(Exception e){        }finally{            System.out.println("finally");        }        System.out.println("end");    }}//輸出in tryfinally

備忘2:
不要在finally語句塊調用return。否則的話。在try語句塊中拋出的異常無法被調用者捕獲,例如以下:

    try {      doSomething();      System.out.println("No Exception Caught!");    } catch (RuntimeException e) {      System.out.println("got it.");    }  }  public static void doSomething() {    try {      throw new RuntimeException();    } finally {      return;    }  }//輸出No Exception Caught!

備忘3:
throw與throws的差別:
throw是在語句塊。程式猿主動拋出一個異常。
throws是在方法的簽名處,說明該方法可能拋出的異常。當有多個異常拋出時,用逗號分隔。

備忘4:
從JDK7開始,同一個try相應的多個catch能夠寫在一起。

Java Exception和Error的差別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.