例外處理機制
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(); } } }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/196887.html
標籤:其他
下一篇:Java例外之自定義例外
