运行时异常或未检查的异常是在执行时发生的异常。其中包括编程错误,例如逻辑错误或 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