Java 程序处理未检查异常

javaobject oriented programmingprogramming更新于 2024/3/21 17:16:17

异常是在程序执行期间(即运行时)发生的意外情况,会中断程序的正常工作。

它可能由于各种原因而发生,例如用户输入非法、设备故障、网络连接丢失、物理限制、代码错误、尝试打开不可用的文件等。

异常主要分为两类 −

  • 已检查异常

  • 未检查异常

这里,我们将处理未检查异常。

未检查异常还包括以下内容−

  • 错误类异常− OutOfMemoryError异常、StackOverflow 异常等

  • 运行时异常类 − Nullpointer Exception、IndexoutOfBoundException 等。

我们将在此学习处理两种最常见的异常类型。这些异常是NullpointerException和IndexoutOfBoundException。

IndexoutOfBoundException

当程序员尝试检索索引大于或等于数组长度的大小(因为数组的索引从 0 开始)的元素时,会出现此异常。遇到此异常时,程序会自动结束。

示例 1

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
    //创建长度为 6 的数组
    int arr[] = { 40, 32, 33, 14, 56, 90 };
    // 尝试检索大于
    // 数组索引大小的元素
    System.out.println(arr[10]);
   }
}

输出

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

示例 2

当用户尝试检索等于数组索引大小的数组元素时。

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args){
    //创建长度为 6 的数组
    int arr[] = { 40, 32, 33, 14, 56, 90 };
    // 尝试检索等于数组索引大小的元素
    // System.out.println(arr[6]);
   }
}

输出

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6
	at ExceptionExample1.main(ExceptionExample1.java:8)

处理 ArrayIndexoutOfBoundException

此异常可通过 try-catch 语句处理。

try 语句使程序员能够定义一个代码块来测试可能的错误,catch 块会捕获给定的异常对象并执行所需的操作。因此,程序将成功执行,而不会像上述情况那样意外停止。

示例

import java.io.*;
public class ExceptionExample1 {
   public static void main(String[] args) {
      
        // 用 6 个数组元素填充数组
        int arr[] = { 40, 32, 33, 14, 56, 90 };
        
        // Try 块用于处理异常
        try {
        
            // 尝试检索并打印
            
            // 超出此数组索引范围的元素
            System.out.println(arr[10]);
        }
        
        // Catch 块用于捕获异常
        catch (ArrayIndexOutOfBoundsException e) {
        
            // 当访问数组中不存在的索引时显示消息
            System.out.println( "数组超出索引,请纠正您的代码");
        }
   }
}

输出

数组超出索引,请纠正您的代码

NullPointerException

当尝试检索具有空值的对象引用时会遇到此异常。

示例

import java.io.*;
public class ExceptionExample2 {
    public static void main(String[] args) {
        // 字符串 str 的实例具有空值
        String str = null;
        // 将空值与其他字符串进行比较
        // 引发异常并打印相同内容
        System.out.println(str.equals("Hello"));
    }
}

输出

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.equals(Object)" because "" is null
	at ExceptionExample2.main(ExceptionExample2.java:8)

处理 NullPointerException

此异常也可以通过 try-catch 语句处理。

示例

import java.io.*;
public class ExceptionExample2 {
   public static void main(String[] args) {
      // 为字符串分配 NULL 值
      String str = null;
      try {
        // 尝试将空值与另一个字符串进行比较
        // 并抛出异常
        if (str.equals("Hello")) {
        // 如果为真,则打印以下字符串
        System.out.println("TRUE");
        }
      }
      catch (NullPointerException e) {
        // 处理异常
        System.out.println("对象引用不能为空");
      }
   }
}

输出

对象引用不能为空

在本教程中,我们讨论了 Java 程序处理未经检查的异常 - NullpointerException 和 IndexoutOfBoundException。


相关文章


有用资源