Java允许在方法的后面使用throws关键字对外声明该方法有可能发生异常,在调用方法时,就明确地知道该方法有异常,并且必须在程序中对异常进行处理,否则编译无法通过。
比如:
public static void main(String[] args) throws Exception {
int result = test(4,0);
System.out.println(result);
test1(1,2);
}
public static int test(int x,int y) throws ArithmeticException {
int result = x/y;
return result;
}
main方法必须抛出比test方法的相同或者父类异常,负责编译是不通过的。
这时候有同学会问,如果跑出的异常不是发生时的异常会怎样呢?
试试,下面代码显然是抛出数组下边越界异常。
public static void main(String[] args) throws IOException {
/*int result = test(4,0);
System.out.println(result);*/
test1(1,2);
}
public static void test1(int x,int y) throws IOException {
int [] arr = new int[1];
arr[1]=y;
}
编译没有问题,运行试试
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at exception.TestException.test1(TestException.java:17)
at exception.TestException.main(TestException.java:9)
抛出的还是真实的异常。
可见,throws关键字对外声明的是该方法有可能发生异常,并不能指定抛出此异常,这种写法的一般是程序员知道潜在的异常并且是可控的,会在上层调用时处理此异常。