//自訂負數異常類 class myException extends Exception { public myException(String msg) //構造方法 { super(msg); //調用Exception異常類的構造方法 } } class Test { public int devide(int x,int y) throws myException //由於方法體內使用了throw,又沒有try....catch進行處理,所以用throws聲明 { if (y<0) throw new myException("異常資訊:被除數小於零。"); //方法內使用了throw拋出了異常對象,如果方法內沒有try....catch語句對這個拋出的異常進行處理,則此方法應聲明拋出異常throws XxxException,由該方法的調用者負責處理。 if (y==0) throw new myException("異常資訊:被除數不能為零。"); return x/y; } } class TestException { public static void main(String [] args) { try { int result=new Test().devide(3,1); //int result=new Test().devide(3,0); //int result=new Test().devide(3,1); System.out.println("the result is "+result); //return; } catch(myException e) { System.out.println(e.getMessage()); //System.exit(0); } /* //ArtthmeticException 算術運算異常類。比如除以零。 catch(ArithmeticException e) { System.out.println("異常資訊:"+e.getMessage()); //調用了異常類的getMessage方法 System.out.print("異常堆棧跡:"); e.printStackTrace(); //調用異常類printStackTrace方法,列印異常詳情 } */ catch(Exception e) //前面沒能處理的所有異常都由Exception處理。由於Exception是所有異常類的父類,所以這句不能放到其他語句的前面。否則編譯的時候會出錯。 { System.out.println("異常資訊:"+e.getMessage()); //return; } finally { System.out.println("the pragram is running into finally"); } //finally語句塊。即使try和catch語句塊使用return語句退出了當前方法或break跳出某個迴圈,相關的finally代碼塊都不會受影響的執行。 //finally代碼塊唯一不能執行的情況是在被保護的代碼塊中執行了System.exit(0) //每個try語句必須有一個或者多個catch語句與之對應,try代碼塊、catch代碼塊及finally代碼塊之間不能有其他語句。 System.out.println("the pragram is running here!"); //當catch語句中使用了return或者System.exit(0)語句是,這裡的代碼就不會執行了。 } }