异常处理小练习
1 package day1_31; 2 3 /** 4 * 异常处理小练习 5 */ 6 public class ExceptionTest { 7 public static void main(String[] args){ 8 try { 9 String[] arr = {"13","6"}; 10 int result = method(arr); 11 System.out.println(result); 12 } catch (Exception e) { 13 System.out.println(e.getMessage()); 14 } 15 } 16 17 public static int method(String[] args) throws RuntimeException { 18 if (args.length != 2) { 19 throw new ArrayIndexOutOfBoundsException("没有输入两个数字"); 20 } 21 int one; 22 int two; 23 try { 24 one = Integer.parseInt(args[0]); 25 two = Integer.parseInt(args[1]); 26 } catch (NumberFormatException e) { 27 throw new NumberFormatException("没有输入数字类型"); 28 } 29 30 if (two == 0) { 31 throw new ArithmeticException("被除数不能为0"); 32 } 33 34 if (one < 0 || two < 0) { 35 throw new MyException("不能输入负数"); 36 } 37 38 return one/two; 39 } 40 }
自定义异常类MyException
1 package day1_31; 2 3 public class MyException extends RuntimeException { 4 static final long serialVersionUID = -3387513124229948L; 5 6 public MyException() { 7 super(); 8 } 9 10 public MyException(String message) { 11 super(message); 12 } 13 14 }