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

Java 自定义异常的创建和使用
引言
自定义异常允许开发人员创建自定义错误消息和异常处理逻辑。在本文中,我们将介绍如何创建和使用 Java 自定义异常,并提供一个实战案例。
立即学习“Java免费学习笔记(深入)”;
创建自定义异常
要创建一个自定义异常类,需要扩展Exception或RuntimeException类:
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中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号