JAVA篇:Java 多執行緒 (五)ThreadLocal詳解
阿新 • • 發佈:2021-10-18
異常處理的五個關鍵字
try、catch、finally、throw、throws
int a = 1; int b = 0; //快捷鍵 CTRL+ALT+T //假設要捕獲多個異常:從小到大 try{ //try監控區域 System.out.println("a/b"); }catch(Exception e){ //catch(想要捕獲的異常型別)捕獲異常 System.out.println("程式出現異常,變數b不能為0"); }catch(Error){ }catch(Throwable t){ }finally{ //finally可以不需要 處理善後工作 System.out.println("finally"); } /*-----------------------------------------------------------------*/ //假設這方法中,處理不了這個異常,方法上丟擲異常 public static void main(String[] args){ try{ new Test().test(1,0); }catch(ArithmeticException e){ e.printStackTrace(); } } //假設者方法中,處理不了這個異常,方法上丟擲異常,增加throws ArithmeticException public void test(int a,int b) throws ArithmeticException{ if(b==0){ //throw throws throw new ArithmeticException(); //主動丟擲異常,一般在方法中使用 } }
自定義異常
//自定義 異常類 public class MyException extends Exception{ //傳遞數字大於10,丟擲異常 private int detail; public MyException(int a){ this.detail = a; } //toString:異常的列印資訊 @Override public String toString(){ return "MyException{"+"detail="+detail+"}"; } } //測試類 public class Test{ static void test(int a) throws MyException{ if(a>10){ throw new MyException(a); //丟擲 } System.out.println("ok"); } } public static void main(String[] args){ try{ test(1); }catch(MyException e){ //可以增加一些處理異常的程式碼 System.out.println("MyException=>"+e); } }