举个例子算术异常:
public class TestException {
public static void main(String[] args) {
int a = 1;
int b = 0;
try { // try监控区域
if (b == 0) throw new ArithmeticException(); // 通过throw语句抛出异常
System.out.println("a/b的值是:" + a / b);
System.out.println("this will not be printed!");
}
catch (ArithmeticException e) { // catch捕捉异常
System.out.println("程序出现异常,变量b不能为0!");
}
System.out.println("程序正常结束。");
}
}
运行结果:
D:\java>java TestException
程序出现异常,变量b不能为0!
程序正常结束。

此博客展示了如何在Java中处理算术异常。代码片段中,当尝试执行除以零的操作时,程序抛出ArithmeticException。通过try-catch块捕获异常,输出错误信息并确保程序正常结束。
https://www.bilibili.com/video/BV1qL411u7eE?spm_id_from=333.999.0.0
1169

被折叠的 条评论
为什么被折叠?



