可在 Java 中处理 RuntimeException 吗?


运行时异常或未经检查的异常是执行时产生的异常。这些包括编程错误,如逻辑错误或 API 使用不当。编译时会忽略运行时异常。

IndexOutOfBoundsException、ArithmeticException、ArrayStoreException 以及 ClassCastException 是运行时异常的示例。

示例

在以下 Java 程序中,我们有一个大小为 5 的数组,并且尝试访问第 6 个元素,这会生成 ArrayIndexOutOfBoundsException

public class ExceptionExample {
   public static void main(String[] args) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      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) {
      //Creating an integer array with size 5
      int inpuArray[] = new int[5];
      //Populating the array
      inpuArray[0] = 41;
      inpuArray[1] = 98;
      inpuArray[2] = 43;
      inpuArray[3] = 26;
      inpuArray[4] = 79;
      //Accessing index greater than the size of the array
      System.out.println( inpuArray[3]);
   }
}

输出

26

更新于: 2020 年 7 月 3 日

101 次浏览

开启你的 职业生涯

完成课程获得认证

立即开始
广告
© . All rights reserved.