- Exception 例外,例外
- 例外處理機制:拋出例外,然后捕獲例外
- try-catch-finally示例
-
int a = 1; int b = 0; try { //監控區域 System.out.println(a/b); }catch (ArithmeticException e){ //catch的引數是想要捕獲的例外型別,可以寫多個catch,并且范圍大的要寫在范圍小的后面,一個例外只會被捕獲一次 System.out.println("除數不能為0"); }finally { //處理善后作業,也可以不寫,一般來關閉IO和資源 System.out.println("finally"); }
-
throw-throws示例
-
public static void main(String[] args) { try { new Student().test(1,0); } catch (ArithmeticException e) { //捕獲test()方法中拋出的例外并處理,程式就不會停止 System.out.println("除數為0"); } finally { System.out.println("結束"); } } public void test(int a,int b) throws ArithmeticException{ //假設方法中無法處理這個例外,再次拋出例外 if (b==0){ throw new ArithmeticException(); //主動拋出的例外,在方法中使用 } }
- IDEA中,ctrl+alt+t,再做出選擇即可快速創建捕獲例外的try,catch,finally陳述句
- 在多重catch塊后面,可以加一個catch(Exception)來處理可能被遺漏的例外
- 在catch捕獲后,盡量去處理例外,而非簡單的列印輸出
- 盡量添加finally陳述句塊去釋放占用的資源,IO,Scanner
-
(1) 創建自定義例外類,繼承exception類即可,最好重寫toString方法(為了方便列印自己的例外資訊)
(2) 在方法中通過throw拋出例外物件
(3) 如果在方法內沒有用try-catch捕獲并處理,那么需要在方法的宣告處通過throws拋出例外給方法呼叫者
(4) 呼叫者捕獲并處理例外
- 例外物件e就是該例外物件的toString()方法回傳值(String型別)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/5958.html
標籤:Java
