我们能处理 Java 中的 RuntimeException 吗?

java 8object oriented programmingprogramming

运行时异常或未经检查的异常是在执行时发生的异常。这些包括编程错误,例如逻辑错误或 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]);
   }
}

运行时异常

线程"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];
      //填充数组
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //访问大于数组大小的索引
      System.out.println( inpuArray[3]);
   }
}

输出

26

相关文章