java:异常处理

1.运行java时,出现了异常:

我这里是因为:arr[3]不存在:
java.lang.ArrayIndexOutOfBoundsException: 3

public class btyf {

    public static void main(String[] args){

      int[] arr={1,2,3};
      System.out.println(arr[0]);
        System.out.println(arr[3]);
System.out.println(arr[1]);


//1 异常
        ArrayIndexOutOfBoundsException  异常名
        // btyf.main(btyf.java:13)      异常位置第13行
        //

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
//	at btyf.main(btyf.java:13)

    }
}

结果:
在这里插入图片描述

java虚拟机:会把异常内容输出控制台
在这里插入图片描述

在这里插入图片描述

2.处理异常:

在这里插入图片描述

public class btyf {

    
    public static void main(String[] args){

        
      int[] arr={1,2,3};
      System.out.println(arr[0]);

      
try{
    System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {
    
    System.out.println("你访问的数组索引不存在");

e.printStackTrace();  //输出异常数据:控制台
}
        System.out.println(arr[1]);

//1 异常
       // ArrayIndexOutOfBoundsException  异常名
        // btyf.main(btyf.java:13)      异常位置

//Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
//	at btyf.main(btyf.java:13)

    }


}

结果:
通过try抓异常,后面没有异常的代码就不会因为前面的代码一些异常而停止,
就可以执行
在这里插入图片描述

3.throwable:成员方法:

System.out.println(e.toString());//打印出异常内容:位置和名称
e.printStackTrace(); //输出异常数据:控制台
System.out.println(e.getMessage()); 一样
多用:System.out.println(e.toString());这个
在这里插入图片描述

try{
    System.out.println(arr[3]);
}catch (ArrayIndexOutOfBoundsException e) {

    //System.out.println("你访问的数组索引不存在");
   // e.printStackTrace();
    System.out.println(e.getMessage());

    
    //public String getMessage() {
    //        return detailMessage;
    //    }
    
    System.out.println(e.toString());
}

结果:
在这里插入图片描述

4.throws:抛出异常:

在这里插入图片描述
但是在异常处:还是要添加try catch

添加位置:异常成员方法
public static void main(String[] args)throws ArrayIndexOutOfBoundsException{}

代码:

public class uytig {


    public static void main(String[] args)throws ArrayIndexOutOfBoundsException{


        int[] arr={1,2,3};
        System.out.println(arr[0]);


        try {
            System.out.println(arr[3]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("执行中");

}


}

在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

半浮名

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

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

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

打赏作者

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

抵扣说明:

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

余额充值