本節關注:Java中錯誤和異常處理的典 型技術——把原理落實到代碼上!html
【Throwable】java
【Error】程序員
【異常按結構層次的分類】數據庫
【異常按處理機制角度的分類】編程
import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
public class NullPointerExceptionExample { public static void main(String args[]){ String str=null; System.out.println(str.trim()); } } Exception in thread "main" java.lang.NullPointerException
【checked和unchecked總結】api
– Checked exception應該讓客戶端從中獲得豐富的信息。 數組
– 要想讓代碼更加易讀,傾向於用unchecked exception來處理程序中的錯誤網絡
【異常中的LSP原則】oracle
【利用throws進行聲明】ide
【利用throw拋出一個異常】
【try-catch語句】
【finally語句】
1 public class ExcepTest{ 2 public static void main(String args[]){ 3 int a[] = new int[2]; 4 try{ 5 System.out.println("Access element three :" + a[3]); 6 }catch(ArrayIndexOutOfBoundsException e){ 7 System.out.println("Exception thrown :" + e); 8 } 9 finally{ 10 a[0] = 6; 11 System.out.println("First element value: " +a[0]); 12 System.out.println("The finally statement is executed"); 13 } 14 } 15 }
拋出檢查型異常:
拋出unchecked exception: