建立一個異常處理方法
阿新 • • 發佈:2021-08-10
1 package com.demo12; 2 // 異常類 3 // 格式: 普通類+ extends Exception,去繼承異常 4 public class MyException extends Exception{ 5 6 //傳遞數字 > 10 7 private int detail; 8 // 通過構造器去書寫異常 9 public MyException(int d){ 10 this.detail = d; 11 } 12 // 通過 toString輸出字串 13 @Override 14 publicString toString() { 15 return "MyException{" + 16 "detail=" + detail + 17 '}'; 18 } 19 }
1 package com.demo12; 2 3 public class Test { 4 // 可能會存在異常的方法 5 // 格式 修飾詞 + 型別 + 方法名(引數型別 引數名) + throws MyException 6 static void test(int a) throws MyException {7 System.out.println("傳遞的引數為:" + a ); 8 if (a > 10){ 9 // 滿足條件,丟擲一個新異常: throw new 新異常(引數) 10 throw new MyException(a); 11 } 12 System.out.println("OK"); 13 } 14 15 public static void main(String[] args) { 16 // 呼叫存在異常的方法。需要使用try/catch17 try { 18 test(12); 19 } catch (MyException e) { 20 System.out.println("MyException==>" + e); 21 } 22 } 23 24 }