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

自定义异常用于创建错误消息和处理逻辑。首先,需继承 exception 或 runtimeexception 创建自定义异常类。然后,可重写 getmessage() 方法设置异常消息。通过 throw 关键字抛出异常。使用 try-cat

自定义异常用于创建错误消息和处理逻辑。首先,需继承 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自定义异常的创建和使用的详细内容,更多请关注叮当号网其它相关文章!

文章来自互联网,只做分享使用。发布者:城南北边,转转请注明出处:https://www.dingdanghao.com/article/436467.html

(0)
上一篇 2024-05-04 06:05
下一篇 2024-05-04 06:05

相关推荐

联系我们

在线咨询: QQ交谈

邮件:442814395@qq.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信公众号