如何在Java中正确处理异常,避免全局污染的问题实例
在Java中,正确处理异常主要是通过使用try-catch-finally结构来实现的。以下是一个实例:
public class ExceptionHandlingExample {
public void dangerousMethod() {
// 这里可能会抛出异常
try {
int divideByZero = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("危险操作导致除以零错误: " + e.getMessage());
}
}
public void safeMethod() {
// 这里不会抛出异常
try {
int result = 15 / 2; // 分母不为0
System.out.println("安全操作结果: " + result);
} catch (ArithmeticException e) {
System.out.println("安全操作导致除以零错误: " + e.getMessage());
}
}
public static void main(String[] args) {
ExceptionHandlingExample example = new ExceptionHandlingExample();
example.dangerousMethod(); // 这里会抛出异常
example.safeMethod(); // 这里不会抛出异常
}
}
在这个例子中,dangerousMethod()
可能会抛出ArithmeticException
(除以零错误),而safeMethod()
则不会抛出任何异常。在main()
方法中,我们分别调用这两个方法来演示如何正确处理异常。
还没有评论,来说两句吧...