Java异常处理:捕获,声明和处理异常的实战案例
在Java编程中,异常处理是一种机制,用来应对程序运行时可能出现的问题。下面我会通过几个实战案例来详细解释。
- 捕获异常:
try {
// 可能出错的操作
int division = 10 / 2;
System.out.println("Division result: " + division);
} catch (ArithmeticException e) {
// 处理除以零的错误
System.out.println("Error: Division by zero!");
} finally {
// 无论是否发生异常,都会执行的操作
System.out.println("This is a finally block.");
}
声明自定义异常:
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
try {
int negativeNumber = -10;
if (negativeNumber > 0) {
throw new InvalidInputException("Negative number can't be greater than zero!");
}
// ... 其他代码
} catch (InvalidInputException e) {
System.out.println(e.getMessage());
}
通过以上案例,你可以看到Java异常处理是如何捕获、声明和处理异常的。在实际编程中,根据需要灵活运用这些知识。
还没有评论,来说两句吧...