JAVA异常

第一步先来个程序

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

解决方法无非就那两种

  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 {

这个地方是一定会执行的语句

 }

最后 像上面这种简单的代码不要犯这种错误了

一直做一个能写出简单易懂代码的人

  • 10
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Carl_Go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值