有个问题想不明白,throws是为了可以使被调用方法的异常向上抛,上层调用必须要有try-catch语句捕获throws异常,那么问题来了,假如我上层调用中有写try-catch捕获异常,我为啥还需要在被调用方法声明中加throws?不是反正都会被捕获吗,加不加throws就无所谓了。
追问:为什么代码1中ThrowsTest类没有throws ArithmeticException不会报错,代码2中没有throws MyException就编译不过了呢?
//代码1
package trycatch;
public class ThrowsTest {
public static void main(String args[]) {
int num1 = 25;
int num2 = 0;
int result;
if(num2 == 0) {
throw new ArithmeticException("这都不会!");
}
result = num1/num2;
System.out.println("结束了" + result);
}
}
//代码2
package trycatch;
public class TryCatch {
public static void main(String args[]) {
int i = 1;
if(i == 1) {
throw new MyException("出错了!");
}
}
}
class MyException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public MyException(String message) {
super(message);
}
}