Java Exception和Error的區別

來源:互聯網
上載者:User

標籤:throw   throws   exception   error   異常   

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.