Java异常处理机制:捕获和重新抛出示例
在Java中,异常处理机制用于处理程序运行过程中可能出现的错误。以下是一个简单的例子,展示了如何捕获和重新抛出异常:
public class ExceptionHandlingExample {
public static void main(String[] args) {
// 捕获try块中的异常
try {
// 会引发ArithmeticException的代码
int division = 10 / 0; // 这会导致"除以零"错误
System.out.println("Division successful, result: " + division); // 不会执行,因为之前抛出了异常
} catch (ArithmeticException e) { // 捕获ArithmeticException类型的异常
System.out.println("Caught arithmetic exception: " + e.getMessage()); // 输出异常信息
// 重新抛出异常,但添加了新的错误消息
throw new ArithmeticException("Divide by zero error. Please check your operation.", e);
}
}
}
在这个例子中,我们尝试进行除法操作(10 / 0
),这会导致ArithmeticException
。我们使用try-catch
块来捕获这个异常,并且重新抛出,但添加了新的错误消息。
这就是Java中异常处理机制的基本应用。
还没有评论,来说两句吧...