自定义异常用于创建错误消息和处理逻辑。首先,需继承 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";
}抛出异常
专为中小型企业定制的网络办公软件,富有竞争力的十大特性: 1、独创 web服务器、数据库和应用程序全部自动傻瓜安装,建立企业信息中枢 只需3分钟。 2、客户机无需安装专用软件,使用浏览器即可实现全球办公。 3、集成Internet邮件管理组件,提供web方式的远程邮件服务。 4、集成语音会议组件,节省长途话费开支。 5、集成手机短信组件,重要信息可直接发送到员工手机。 6、集成网络硬
可以通过使用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










