淺析Java中的異常處理機制
阿新 • • 發佈:2020-11-30
異常處理機制
1、丟擲異常
2、捕獲異常
3、異常處理五個關鍵字:
try、catch、finally、throw、throws
注意:假設要捕獲多個異常:需要按照層級關係(異常體系結構) 從小到大!
package exception; /** * Java 捕獲和丟擲異常: * 異常處理機制 * 1、丟擲異常 * 2、捕獲異常 * 3、異常處理五個關鍵字 * try、catch、finally、throw、throws * 注意:假設要捕獲多個異常:需要按照層級關係(異常體系結構) 從小到大! */ public class Test { public static void main(String[] args) { int a = 1; int b = 0; /** * try catch 是一個完整的機構體,finally 可以不要 * 假設IO流,或者跟資源相關的東西,最後需要關閉,關閉的操作就放在 finally 中 */ try { //try 監控區域 System.out.println(a / b); } catch (ArithmeticException exception){ //catch(想要捕獲的異常型別) 捕獲異常 System.out.println("程式出現異常,變數b不能為0"); } finally { //處理善後工作 System.out.println("finally"); } System.out.println("-------------- 分隔符 --------------"); try { new Test().a(); //無限迴圈 } catch (Error error){ System.out.println("Error"); } catch (Exception exception){ System.out.println("Exception"); } catch (Throwable throwable){ System.out.println("Throwable"); } finally { System.out.println("finally"); } } public void a(){ b(); } public void b() { a(); } }
捕獲異常
快捷鍵:選中程式碼 Ctrl + Alt + T
捕獲異常的好處:程式不會意外的停止,try catch 捕獲異常後程序會正常的往下執行
package exception; /** * 捕獲異常快捷鍵 * 選中程式碼後:Ctrl + Alt + T * 如: * 選中 System.out.println(a / b); * 然後快捷鍵 Ctrl + Alt + T */ public class Test2 { public static void main(String[] args) { int a = 1; int b = 0; try { System.out.println(a / b); } catch (Exception exception) { exception.printStackTrace(); //列印錯誤的棧資訊 } finally { } } }
丟擲異常
1、在方法中丟擲異常:throw
2、在方法上丟擲異常:throws
package exception; /** * 捕獲異常 * 丟擲異常 */ public class Test3 { public static void main(String[] args) { /** * 方法中丟擲異常 */ new Test3().test(1,0); //匿名內部類直接呼叫 System.out.println("------------ 分隔符 -------------"); /** * 方法上丟擲異常 * 捕獲異常的好處: * 程式不會意外的停止,try catch 捕獲異常後程序會正常的往下執行 */ try { new Test3().test2(1,0); //匿名內部類直接呼叫 } catch (ArithmeticException e) { e.printStackTrace(); } } /** * 在方法中丟擲異常:throw * @param a * @param b */ public void test(int a,int b){ if (b == 0){ //throw throw new ArithmeticException(); //主動丟擲異常,一般在方法中使用 } System.out.println(a / b); } /** * 假設在方法中處理不了這個異常,就在方法上丟擲異常,然後捕獲異常 * 在方法上丟擲異常:throws * @param a * @param b * @throws ArithmeticException */ public void test2(int a,int b) throws ArithmeticException{ if (b == 0){ throw new ArithmeticException(); } } }
以上就是淺析Java中的異常處理機制的詳細內容,更多關於Java 異常處理機制的資料請關注我們其它相關文章!