Java异常处理:捕获与抛出示例
在Java编程中,异常处理是一种机制,用于在程序运行过程中遇到错误时进行适当的处理。这里我们将通过几个具体的例子来展示如何捕获和抛出异常。
1. 捕获异常
当一个方法可能会抛出某种特定类型的异常时,我们可以使用try-catch语句块来捕获这个异常。
public void divideNumbers(int numerator, int denominator) {
try {
if (denominator == 0) {
throw new IllegalArgumentException("Denominator cannot be zero.");
}
int result = numerator / denominator;
System.out.println("Result: " + result);
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
} finally {
System.out.println("Division complete, regardless of errors.");
}
}
2. 抛出异常
除了捕获异常,Java也允许我们抛出自定义的异常。
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// 示例:当输入值为零时,抛出自定义异常
public void divideZero(int numerator, int denominator) throws CustomException {
if (denominator == 0) {
throw new CustomException("Denominator cannot be zero.");
}
// ... 其他代码
}
总结来说,在Java编程中,异常处理主要涉及两种操作:捕获异常并进行相应处理,以及抛出自定义的异常。
还没有评论,来说两句吧...