Java--RuntimeException运行时异常--Arr

2022-09-13  本文已影响0人  李赫尔南

  当程序访问一个数组的某个元素时,如果这个元素的索引超出了0~数组长度-1这个范围,则会出现数组下标越界异常(ArrayIndexOutOfBoundsException)。

【示例】ArrayIndexOutOfBoundsException异常

public class Test{
    public static void main(String[] args){
        int [] arr = new int[5];
        system.out.println(arr[5]);
    }
}

输出:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at Test.main (Test.java: 4)

  解决数组索引越界异常的方式,增加关于边界的判断:

public class Test{
    public static void main(String[] args){
        int [] arr = new int[5];
        int a = 5;
        if (a < arr.length) {
            System.out.println(arr [a]);
        }
    }
}

  在使用包装类将字符串转换成基本数据类型时,如果字符串的格式不正确,则会出现数字格式异常(NumberFormatException)。
Java--RuntimeException运行时异常--NumberFormatException异常

上一篇 下一篇

猜你喜欢

热点阅读