A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑马—张帅 中级黑马   /  2014-6-9 16:20  /  1174 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. class Demo2
  2. {
  3.           int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException
  4.      {
  5.           int []arr=new int [a];
  6.         System.out.println(arr[4]);
  7.           return a/b;
  8.      }
  9. }
  10. public class ExceptionDemo2
  11. {
  12.                public static void main(String[]args)
  13.        {
  14.              Demo2 d=new Demo2();
  15.        try
  16.          {
  17.               int x=d.div(1, 1);
  18.               System.out.println("x="+x);
  19.          }
  20.        catch(ArithmeticException e)
  21.       {
  22.          System.out.println(e.toString());
  23.          System.out.println("被零除了!!");
  24.       }
  25.        catch(ArrayIndexOutOfBoundsException e)
  26.      {
  27.         System.out.println(e.toString());
  28.         System.out.println("角标越界了!!");
  29.      }
  30.    }

  31. }
复制代码

看毕老师的视频,在异常处理这一块儿,以上程序在myEclipse上运行时,一直出现角标越界的提示,不管角标改成什么都不行,求大神指点迷境。

1111.jpg (37.04 KB, 下载次数: 2)

1111.jpg

5 个回复

倒序浏览
  1. class Demo2
  2. {
  3.           int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException
  4.      {
  5.         int []arr=new int [a];
  6.         System.out.println(arr[4]);
  7.           return a/b;
  8.      }
  9. }
  10. 这个类的div方法中的System.out.println(arr[4]);是干嘛的?目测没有任何意义
复制代码
回复 使用道具 举报
晕~int x=d.div(1, 1);
你调用int div(int a,int b)
这时 a=1 b =1
而你声明 int []arr=new int [a]; 这个数组的长度是1.
你传个4肯定出现越界异常。
如果你传个0 。 运行就没错了,
回复 使用道具 举报

我才看到这一行。。的确没用上面已经声明过长度了。。
回复 使用道具 举报
唐坚 发表于 2014-6-9 18:22
晕~int x=d.div(1, 1);
你调用int div(int a,int b)
这时 a=1 b =1

正解:handshake
回复 使用道具 举报
你在调用Demo2的div方法时,你传递的参数a的值应该必须是大于等于5的,这样就不会有角标越界的问题了,因为你在div方法中定义了int[] arr数组,有打印arr[4]的值。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马