qq_36647760 2016-11-08 05:58 采纳率: 0%
浏览 2932

请编写一个捕获异常的小程序:计算二个数的商,分别捕获数组越界、数据格式不正确、除数为零三种异常。

请编写一个捕获异常的小程序:计算二个数的商,分别捕获数组越界、数据格式不正确、除数为零三种异常。

  • 写回答

1条回答 默认 最新

  • 毕小宝 博客专家认证 2016-11-08 07:49
    关注

    也不复杂啊,定义三个函数,操作放在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);
        }
    
    }
    
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器