如何在Java中处理ArrayStoreException(非受检异常)?


java.lang.ArrayStoreException 是一个非受检异常,当试图将某种类型的对象存储到不同类型的对象数组中时,可能会发生此异常。通常,你会遇到java.lang.ArrayStoreException: java.lang.Integer,这种情况发生在尝试将整数存储到不同类型的数组中时,例如字符串数组或浮点数数组等。

示例1

在线演示

public class ArrayStoreExceptionTest {
   public static void main(String[] args) {
      Object[] names = new Float[2];
      names[1] = new Integer(2);
   }
}

输出

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Integer
        at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:4)

在上述程序中,发生了java.lang.ArrayStoreException: java.lang.Integer

  • java.lang.ArrayStoreException: 当尝试将java.lang.Integer类型的对象存储到java.lang.Float类型的数组中时,Java 语言抛出的异常。
  • java.lang.Integer: 尝试存储到不同类型数组中的Integer类型对象。

如何处理ArrayStoreException

我们可以使用try...catch 块来处理ArrayStoreException

  • try...catch 块包围可能抛出ArrayStoreException的语句。
  • 我们可以捕获ArrayStoreException
  • 对我们的程序采取必要的措施,因为我们正在处理异常,并且执行不会中断。

示例2

在线演示

public class ArrayStoreExceptionTest {
   public static void main(String[] args) {
      Object[] names = new Float[2];
      try {
         names[1] = new Integer(2);
      } catch (ArrayStoreException e) {
         e.printStackTrace();
         System.out.println("ArrayStoreException is handled");
      }
      System.out.println("Continuing with the statements after try and catch blocks");
   }
}

输出

ArrayStoreException is handled
Continuing with the statements after try and catch blocks
java.lang.ArrayStoreException: java.lang.Integer
      at ArrayStoreExceptionTest.main(ArrayStoreExceptionTest.java:5)


在上面的例子中,当发生异常时,执行从异常发生点跳转到catch块。它执行catch块中的语句,然后继续执行try...catch块后面的语句。

更新于:2020年2月24日

251 次浏览

启动你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.