首页  >  文章  >  Java  >  Java自定义异常的创建和使用

Java自定义异常的创建和使用

WBOY
WBOY原创
2024-05-03 22:27:011040浏览

自定义异常用于创建错误消息和处理逻辑。首先,需继承 Exception 或 RuntimeException 创建自定义异常类。然后,可重写 getMessage() 方法设置异常消息。通过 throw 关键字抛出异常。使用 try-catch 块处理自定义异常。本文提供了一个解析整数输入的实战案例,在输入不为整数时抛出自定义 InvalidInputException 异常。

Java自定义异常的创建和使用

Java 自定义异常的创建和使用

引言

自定义异常允许开发人员创建自定义错误消息和异常处理逻辑。在本文中,我们将介绍如何创建和使用 Java 自定义异常,并提供一个实战案例。

创建自定义异常

要创建一个自定义异常类,需要扩展ExceptionRuntimeException类:

public class MyCustomException extends Exception {
    // ...
}

设置异常消息

可以覆盖getMessage()方法以自定义异常消息:

@Override
public String getMessage() {
    return "Custom exception message";
}

抛出异常

可以通过使用throw关键字抛出自定义异常:

throw new MyCustomException("Custom exception message");

使用自定义异常

可以使用try-catch块来处理自定义异常:

try {
    // 代码可能引发 MyCustomException
} catch (MyCustomException e) {
    // 处理 MyCustomException
}

实战案例

假设我们有一个方法来处理用户输入的整数,并希望在输入不为整数时抛出自定义异常。我们可以使用以下自定义异常:

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

在处理整数输入的方法中,我们可以抛出InvalidInputException

public int parseInteger(String input) {
    try {
        return Integer.parseInt(input);
    } catch (NumberFormatException e) {
        throw new InvalidInputException("Invalid input: " + input);
    }
}

在主方法中,我们调用parseInteger()方法并处理InvalidInputException

public static void main(String[] args) {
    try {
        int number = parseInteger("abc");
    } catch (InvalidInputException e) {
        System.out.println(e.getMessage());
    }
}

输出:

Invalid input: abc

以上是Java自定义异常的创建和使用的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn