黑马程序员技术交流社区

标题: 关于异常抛出处理 [打印本页]

作者: 黑马—张帅    时间: 2014-6-9 16:20
标题: 关于异常抛出处理
  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

作者: shisishishisi    时间: 2014-6-9 18:22
  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]);是干嘛的?目测没有任何意义
复制代码

作者: 唐坚    时间: 2014-6-9 18:22
晕~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-10 07:36
shisishishisi 发表于 2014-6-9 18:22

我才看到这一行。。的确没用上面已经声明过长度了。。
作者: 黑马—张帅    时间: 2014-6-10 07:41
唐坚 发表于 2014-6-9 18:22
晕~int x=d.div(1, 1);
你调用int div(int a,int b)
这时 a=1 b =1

正解:handshake
作者: 喜爱    时间: 2014-6-10 09:24
你在调用Demo2的div方法时,你传递的参数a的值应该必须是大于等于5的,这样就不会有角标越界的问题了,因为你在div方法中定义了int[] arr数组,有打印arr[4]的值。




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2