创建自定义 Java 异常

JavaJavaBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在 Java 中,异常(exceptions)用于指示程序执行过程中发生的异常事件。虽然 Java 提供了许多内置的异常,但有时我们可能需要为特定情况定义自己的自定义异常。自定义异常分为两种类型:受检异常(checked exceptions)和非受检异常(unchecked exceptions)。受检异常需要在编译时处理,而非受检异常仅在运行时才会被检测到。在本实验中,我们将创建这两种类型的自定义异常,并学习如何使用它们。

创建一个名为 MyArray 的 Java 类

首先,我们将创建一个名为 MyArray 的 Java 类,用于实现一个带有 get() 方法的数组,该方法在索引无效时可能会抛出异常。

public class MyArray {
    int[] array;

    public MyArray(int size) {
        array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = i * 5;
        }
    }

    // Get method that may throw an exception
    public int get(int index) {
        if (index >= array.length) {
            throw new IndexOutOfBoundsException("Index " + index + " is invalid.");
        } else {
            return array[index];
        }
    }
}

创建一个自定义受检异常(Checked Exception)

我们可以通过继承 Exception 类来创建一个自定义的受检异常(checked exception)。在这个例子中,当索引无效时,我们将创建一个 IndexNotValidException。该异常将由 MyArray 类中的 get() 方法抛出。

public class IndexNotValidException extends Exception {
    public IndexNotValidException(String message) {
        super(message);
    }
}

现在,我们可以更新 MyArray 类中的 get() 方法,使其抛出这个自定义异常。

public int get(int index) throws IndexNotValidException {
    if (index >= array.length) {
        throw new IndexNotValidException("Index " + index + " is invalid.");
    } else {
        return array[index];
    }
}

处理自定义受检异常(Checked Exception)

为了处理自定义的受检异常(checked exception),我们需要在 Demo 类中调用 get() 方法时捕获它,或者使用 throws 关键字声明它。

public class Demo {
    public static void main(String[] args) {
        MyArray arr = new MyArray(5);
        try {
            System.out.println(arr.get(10)); // Throws IndexNotValidException
        } catch (IndexNotValidException e) {
            System.err.println(e.getMessage());
        }
    }
}

创建一个自定义非受检异常(Unchecked Exception)

我们可以通过继承 RuntimeException 类而不是 Exception 类来创建一个自定义的非受检异常(unchecked exception)。在以下示例中,当索引无效时,我们将创建一个 IndexNotValidRuntimeException,该异常将由 MyArray 类中的 get() 方法抛出。

public class IndexNotValidRuntimeException extends RuntimeException {
    public IndexNotValidRuntimeException(String message, Throwable cause) {
        super(message, cause);
    }
}

此外,我们定义了一个可抛出的异常(throwable exception),用于定义底层异常或我们异常的原因。在我们的例子中,底层异常是 ArrayIndexOutOfBounds。我们可以更新 MyArray 类中的 get() 方法,使其抛出这个自定义的非受检异常。

public int get(int index) {
    if (index >= array.length) {
        Throwable cause = new ArrayIndexOutOfBoundsException();
        throw new IndexNotValidRuntimeException("Index " + index + " is invalid.", cause);
    } else {
        return array[index];
    }
}

处理自定义非受检异常(Unchecked Exception)

我们不需要捕获或声明自定义的非受检异常(unchecked exception)。在以下示例中,当在 Demo 类中使用无效索引调用 get() 方法时,将抛出 IndexNotValidRuntimeException

public class Demo {
    public static void main(String[] args) {
        MyArray arr = new MyArray(5);
        System.out.println(arr.get(10)); // Throws IndexNotValidRuntimeException
    }
}

总结

自定义 Java 异常可以帮助我们通过创建符合需求的异常来有效处理应用程序中的特定错误或异常。在本实验中,我们学习了如何创建自己的自定义异常来处理业务逻辑或工作流中的错误。我们还讨论了如何创建受检异常(checked exception)和非受检异常(unchecked exception),并提供了每种类型的示例。