public class ArithmeticExample {
public static void main(String[] args) {
try {
int result = divide(10, 0);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static int divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("n");
}
return a / b;
}
}
divide 方法尝试进行除法运算。如果除数 b 为 0,则会抛出一个 ArithmeticException,并传递字符串 "n" 作为异常消息。main 方法中,我们调用 divide(10, 0) 并捕获可能抛出的 ArithmeticException,然后打印错误信息。下一篇:java finalize
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站