標籤: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的區別