異常處理五個關鍵字:try,catch,finally,throw,throws
捕獲異常
try、catch、finally
package oop.demo10; public class Outer { public static void main(String[] args) { int a = 1; int b =0; //捕獲多個異常:范圍從小到大 try {//try監控區域 System.out.println(a/b); } catch (Error e) {//catch(想要捕獲的異常類型)捕獲異常 System.out.println("Error"); } catch (Exception e) { System.out.println("Exception"); }catch (Throwable e) { System.out.println("Throwable"); }finally {//處理善后工作 System.out.println("finally"); } } }
選中代碼:Ctrl+Alt+T快捷鍵
拋出異常
throw:一般用於方法中拋出異常
throws:在方法上拋出異常
package oop.demo10; public class Outer { public static void main(String[] args) { new Outer().test(1,0); } //假設方法中,處理不了這個異常。那就通過throws在方法上拋出異常 public void test(int a,int b) throws ArithmeticException{ if (b==0){ throw new ArithmeticException();//throw 主動拋出異常 }else{ System.out.println(a/b); } } }