前面总结了由系统抛出异常的情形,基本上,就算不写捕捉异常的语句,系统也会把异常抛出来并中止程序的运行。
但是有时候,需要开发者自己设计抛出异常的方式,这样就用到了throw和throws关键字。
throw是在方法中抛出异常,而throws是在方法声明的时候抛出异常
下面是一个在程序中使用throw关键字抛出异常的例子:
public class testThrow{
static int add(int a,int b){
if(b==0) //如果除数为0,就抛出一个异常
throw new ArithmeticException("There is an error!"); //先new一个异常对象,然后由throw关键字抛出,并附带一个字符串参数
else
return a/b;
}
public static void main(String[] args){
int a = 1, b=0;
add(a,b); //调用静态方法
}
}
如果在方法中没有定义捕捉和处理异常的语句,也可以在方法声明的时候使用throws关键字抛出异常,给方法的调用处来处理,比如:
public class testThrows{
void addArray(int[] a)throws ArrayIndexOutOfBoundsException{ //抛出数组下标越界异常
int x1 = a[5]; //下标越界
}
public static void main(String[] args){
int[] b = {1,0,3};
try{ //准备检查异常
new testThrows().addArray(b);
}catch(ArithmeticException e){ //捕捉算数异常
System.out.println("There is an ArithmeticException.");
}catch(ArrayIndexOutOfBoundsException e2){ //捕捉数组下标越界异常
System.out.println("ArithmeticException");
}
}
}
编译执行