Java异常处理:自定义Exception的使用示例
在Java中,自定义Exception是一种强大的工具,用于表示特定类型的程序错误。以下是一个使用自定义Exception的简单示例:
// 创建自定义异常类
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 示例:当输入的数据不符合要求时抛出自定义异常
public class Main {
public static void main(String[] args) {
try {
// 假设这里需要处理用户输入的数据
int number = Integer.parseInt(args[0]); // 错误的代码,假设输入为"abc"
if (number > 10) { // 正确的条件检查,如果数字大于10,抛出自定义异常
throw new CustomException("Input number exceeds 10.");
}
} catch (CustomException e) {
System.err.println("Error: " + e.getMessage());
} catch (Exception e) {
System.err.println("Unexpected error: " + e);
}
}
}
在这个示例中,我们创建了一个名为CustomException
的自定义异常类,并在处理用户输入数据时抛出这个自定义异常。
还没有评论,来说两句吧...