Excepiton分兩類:checked exception、runtime exception;直接繼承自Exception就是checked exception,繼承自RuntimeException就是runtime的exception。
你可以簡單地理解checked exception就是要強制你去處理這個異常(不管你throws多少層,你終歸要在某個地方catch它);而runtime exception則沒有這個限制,你可以自由選擇是否catch。
那些強制異常處理的代碼塊,必須進行異常處理,否則編譯器會提示“Unhandled exception type Exception”錯誤警告。
舉例子:
1、IndexOutOfBoundsException是RuntimeException的一種,方法體內手動throw了一個異常,但是rangeCheckForAdd()定義處不用寫 throws……
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
2、
public void getName() throws IOException {
throw new FileNotFoundException(); // checked exception
}