異常的處理和throw與try...catch...(finally...)
阿新 • • 發佈:2018-12-01
文章儘量做到簡練概述
通過對異常的分類和處理方式來理解有關異常的認識和處理
-
異常分類
-
異常處理
-
throws和try..catch...(finnaly...)程式碼例項
-
溫馨提示:規範與常見異常(interview)
Exception分為編譯時異常和執行時異常
- 編譯時異常必須處理
- 處理分為JVM處理--手動處理(丟擲和捕獲)
在此不過多講述知識面的內容,很多書本和資料都有,只希望看完這篇文章可以清晰的處理異常,什麼時候怎麼用Throws和try...catch...
方式(1):thorws-->在出現異常的方法上,將異常丟擲給呼叫者,呼叫者也可以繼續把這個異常丟擲去
public static void main(String[] args) throws FileNotFoundException { System.out.println("開始"); copy(); // 此時這裡必須處理這個編譯時異常 System.out.println("結束");//不列印 } /*public static void main(String[] args){ System.out.println("程式開始"); try { copy(); // 此時這裡必須處理這個編譯時異常 } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("程式結束"); }*/ public static void copy() throws FileNotFoundException { File file = new File("D:/meinv.jpg"); // 自動出現一個編譯時異常: 編譯時異常編譯階段必須處理 InputStream is = new FileInputStream(file); }
方式(2):try...catch...-->捕獲並處理異常
格式 : try{ * // 可能出現異常的程式碼 * } catch(異常的型別 變數){ * // 如何處理 * }
提示:異常型別可以多個,也可以直接用Exception(不推薦)
public static void main(String[] args){ System.out.println("程式開始"); copy(); // 此時這裡必須處理這個編譯時異常 System.out.println("程式結束"); } public static void copy() { File file = new File("D:/meinv.jpg"); try { // 自動出現一個編譯時異常: 編譯時異常編譯階段必須處理 // 出現異常 自己解決! InputStream is = new FileInputStream(file); } catch (FileNotFoundException e) { // 輸出異常資訊,列印異常棧資訊!程式不會死亡了,因為自己處理了! e.printStackTrace(); } }
在以上程式碼中演示了,在main方法呼叫自定義方法,對編譯異常的處理,
第1段程式碼在方法中丟擲,呼叫者必須處理,可以繼續丟擲或者try...catch...
第2段程式碼如果已經try...catch...代表已經捕獲並處理異常,在主方法中並不會報錯,不影響後面程式碼的執行
理解好以上編譯時異常,那麼接下來更好接受執行時異常的處理!!!
執行時異常的處理:
在編譯階段,執行時異常即使不處理也不會報錯!
執行時異常是無需通過 throws 往外丟擲的,自動丟擲的,程式設計師無需理會!
public static void main(String[] args) {
try{
System.out.println(chu(1,0));
}catch (ArithmeticException e){
e.printStackTrace(); // 打出異常資訊
System.out.println("我攔截到了異常!");
}
System.out.println("繼續執行!");
}
public static int chu(int a , int b){ //throws ArithmeticException{
System.out.println(a);
System.out.println(b);
// ArithmeticExceptio 數學運算異常
int c = a / b ;
return c ;
}
提示:在規範中異常都應該處理
所以要考慮的只是,在哪個方法try...catch...;為不影響後面程式碼執行,即使不處理不報錯,都應該選擇try...catch...
拓展:
在try...catch...中,可以一個try...catch...catch...多個;也可以catch(異常1 | 異常2 ...變數)
注意:異常的級別關係
finally : 作用只有一個.關閉資源(無論程式是否出現異常,最終一定會執行一次finally)
釋放資源,節約資源!
JDK1.7以後資源關閉的新方式:
try(
// 只能放資源,就會在資源用完以後會自動關閉,程式設計師無需理會!
){
}catch (Exception e){
e.printStackTrace();
}
自定義異常
throw new 異常類名(引數);
提示:在自定義一個RunnableException異常子類,在throw new 方法上不需要丟擲throws(會有提示)
自定義異常的步驟:
* 定義一個異常的子類:XxxException
* 繼承關係:RuntimeException或Exception
* 提供構造方法:無引數和有引數構造方法
throws 在方法上丟擲異常
throw 建立並從這裡丟擲異常
最後:
編譯時常見異常:
FileNotFoundException 檔案找不到異常!
執行是異常:
ArrayIndexOutOfBoundsException 陣列索引越界異常
NumberFormatException 數字轉換異常
NullPointerException 空指標異常
ClassCastException 強制型別轉換異常
面試可能會問到.