第一步先来个程序
package com.liu.ww;
public class AbnormalTest {
public static void main(String[] args) {
int[] arr = new int[5];
for (int i = 0; i < arr.length+1; i++) {
arr[i]=i+1;
}
for(int j : arr){
System.out.println(j);
}
}
}
这个程序就出现了错误
关键在那:ArrayIndexOutOfBoundsException就是这一句(像这种错误异常提示,多看多记忆)
意思是什么?
-
抛出以表示使用非法索引访问数组。 索引为负数或大于或等于数组的大小。
错误代码
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at com.liu.ww.AbnormalTest.main(AbnormalTest.java:7)
进程已结束,退出代码为 1
解决方法无非就那两种
- 一种直接抛出(主方法的位置使用throws)
抛出也是抛出这个异常吧
public class AbnormalTest { //这一句是主要要看的 public static void main(String[] args) throws ArrayIndexOutOfBoundsException{ int[] arr = new int[5]; for (int i = 0; i < arr.length+1; i++) { arr[i]=i+1; } for(int j : arr){ System.out.println(j); } } }
学完第一张方法我们要知道一切皆可抛(关键你要记住那些异常)
第二种是(第二种方法更加安全)
第一种形式
try { 可能会出现的异常 }catch (异常 变量(一般设为e)){ e.printStackTrace() //这个地方无非就是最后输出这个结果 }
(如果你没看懂,先看看代码)第二种形式
try (可能会出现的异常){ //这种形式更多会在IO流种学习
可能会出现的异常
}catch (异常 变量(一般设为e)){
e.printStackTrace() //这个地方无非就是最后输出这个结果
}
还是上面那个问题吧,,第二种方法
public class AbnormalTest {
public static void main(String[] args){
int[] arr = new int[5];
try {
for (int i = 0; i < arr.length+1; i++) {
arr[i]=i+1;
for(int j : arr){
System.out.println(j);
}
}
}catch (ArrayIndexOutOfBoundsException e){
e.printStackTrace();
}
}
}
既然的提到这
加入一个finally
try {
可能会出现的异常
}catch (异常 变量(一般设为e)){
e.printStackTrace() //这个地方无非就是最后输出这个结果
}finally {这个地方是一定会执行的语句
}
最后 像上面这种简单的代码不要犯这种错误了
一直做一个能写出简单易懂代码的人