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

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自定义异常的创建和使用的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!