Java中异常处理:自定义异常案例
在Java中,我们可以通过继承内置的Exception类或者自定义一个新的异常类来实现异常处理。下面以自定义异常为例进行展示:
- 创建自定义异常类
// 自定义一个简单类型的异常
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
- 使用自定义异常
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 1. 显示正常操作
System.out.println("Normal operation");
// 2. 调用可能会抛出异常的方法
try {
// 2.1 验证用户输入,这里故意输入错误数据
String wrongInput = "Invalid input";
processUserInput(wrongInput);
// 2.2 正常情况下的操作,不会引发任何异常
System.out.println("Additional operation");
} catch (CustomException e) {
// 3. 处理自定义异常
System.out.println("Error occurred: " + e.getMessage());
// 可以选择是否继续执行后面的代码
}
}
// 假设这里是一个处理用户输入的方法
private static void processUserInput(String input) {
if (input.isEmpty()) {
throw new CustomException("Input cannot be empty.");
} else {
System.out.println("Processed input: " + input);
}
}
}
上述代码展示了如何自定义一个异常类,然后在可能抛出异常的代码块中捕获这个自定义异常,并进行相应的处理。
还没有评论,来说两句吧...