java - “抛出 ArithmeticException”是否只是方法定义中的装饰?
问题描述
我决定throws ArithmeticException
在下面的代码中删除,当我除以零并出现堆栈跟踪时,我仍然得到相同的结果。在方法定义中是throws ArithmeticException
可选的吗?它的目的是什么?
public static int quotient(int numerator, int denominator) throws ArithmeticException {
return numerator / denominator;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int denominator = scanner.nextInt();
System.out.println(quotient(10, denominator));
} catch(ArithmeticException e) {
System.out.println("Aritmetic exception");
} catch(InputMismatchException e) {
System.out.println("InputMismatchException");
}
}
解决方案
ArithmeticException
是 的子类RuntimeException
,与大多数异常不同,RuntimeException
s 是未经检查的,因此不需要在声明中throws
声明。所以是的,这是不必要的。
推荐阅读
- julia - 在 Julia 中创建随机 SIR 模型
- c# - 系统在C#中通过Process模块运行命令时找不到指定的文件
- java - Firebase Cloud Firestore:查询未更新 Android 中的 ArrayList
- reactjs - 如何使用嵌套值监听 formik 字段的变化?
- excel - 通过查找关联行来构建依赖选项列表
- python - Python中magrittr中tidiverse的点占位符功能,特别是Pandas
- android - 如何从 Android 应用程序查看 Adobe Launch 数据?
- visual-studio-code - vscode 是否有可用的原子样式文件树关闭和打开功能?
- multithreading - 如何处理 Gtk-rs 线程中不可恢复的错误?
- python-3.x - 一个类只是一个模板,还是它本身也是一个实例?