请编写一个捕获异常的小程序:计算二个数的商,分别捕获数组越界、数据格式不正确、除数为零三种异常。
1条回答 默认 最新
关注 也不复杂啊,定义三个函数,操作放在try-catch语句中,校验参数进行相应的处理。然后就是main测试函数传入异常所需的参数。参考:
public class TestException { public static void testZero(int a,int b){ try{ System.out.println("a/b="+(a/b)); }catch(Exception e){ System.out.println(e.getLocalizedMessage()); } } public static void testIndexOutofArray(int[] a){ try{ int len = a.length; System.out.println("a.index of leng+1"+(a[len])); }catch(Exception e){ System.out.println(e.getLocalizedMessage()); } } public static void testIllegalArgument(int day){ try{ if(day<0){ throw new IllegalArgumentException("日期不能为负数."); } }catch(Exception e){ System.out.println(e.getLocalizedMessage()); } } public static void main(String[] args) { testZero(1,0); int [] array = {1,2}; testIndexOutofArray(array); testIllegalArgument(-1); } }
解决 2无用 1