java 中怎么处理 RuntimeException 异常
运行时异常或未检查的异常是在执行时发生的异常。其中包括编程错误,例如逻辑错误或API使用不当。运行时异常在编译时被忽略。
IndexOutOfBoundsException,ArithmeticException,ArrayStoreException和ClassCastException是运行时异常的示例。
示例
在下面的Java程序中,我们有一个大小为5的数组,并且试图访问第6个元素,这将抛出异常ArrayIndexOutOfBoundsException。
public class ExceptionExample {
public static void main(String[] args) {
//创建大小为5的整数数组
int inpuArray[] = new int[5];
//填充数组
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//访问大于数组大小的索引
System.out.println( inpuArray[6]);
}
}运行时异常
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6 at MyPackage.ExceptionExample.main(ExceptionExample.java:14)
处理运行时异常
您可以处理运行时异常并避免异常终止,但是Java中没有针对运行时异常的特定修复程序,具体取决于异常,所需更改代码的类型。
例如,如果您需要在上面列出的第一个程序中修复ArrayIndexOutOfBoundsException,则需要删除/更改访问数组索引位置超出其大小的行。
public class ExceptionExample {
public static void main(String[] args) {
//创建大小为5的整数数组
int inpuArray[] = new int[5];
//Populating the array
inpuArray[0] = 41;
inpuArray[1] = 98;
inpuArray[2] = 43;
inpuArray[3] = 26;
inpuArray[4] = 79;
//访问大于数组大小的索引
System.out.println( inpuArray[3]);
}
}输出结果
26
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短