在 Java 中,异常可以通过使用 'throw' 关键字手动抛出。以下是抛出异常的基本语法:

throw new ExceptionType('Exception Message');

其中,'ExceptionType' 是要抛出的异常类型,可以是 Java 内置的异常类(如 'NullPointerException'、'IllegalArgumentException' 等),也可以是自定义的异常类。'Exception Message' 是异常的详细描述,用于提供关于异常原因的更多信息。

以下是一个示例,演示如何手动抛出一个自定义异常:

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

public class Main {
    public static void main(String[] args) {
        try {
            throw new CustomException('This is a custom exception');
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

在上面的示例中,我们定义了一个名为 'CustomException' 的自定义异常类,它继承自 'Exception'。然后在 'main' 方法中,我们使用 'throw' 关键字抛出了一个 'CustomException' 异常,并通过 'catch' 块捕获并处理了该异常。最后,我们打印了异常的消息。

请注意,当抛出异常时,程序的执行将立即跳转到最近的异常处理程序 ('catch' 块)。如果没有找到匹配的 'catch' 块,则程序将终止并显示异常的堆栈跟踪信息。

Java 异常抛出:完整指南及示例

原文地址: https://www.cveoy.top/t/topic/pZSk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录