throw关键字用在代码块中, 根据具体情况显式地抛出异常,每次只能抛出一个异常对象。
当throw语句执行时,立即停止当前方法的执行。
int a = -1;
if(a < 0){
throw new IndexOutOfBoundsException("数值越界");
}
throw关键字是在方法声明上使用的,告诉调用者可能抛出的异常类型,如果发生了异常,则抛给调用者,可以声明多个异常类型。
public static void method() throws IndexOutOfBoundsException{
try {
int[] a = {1,2,3};
int b= a[3];
}catch (IndexOutOfBoundsException e){
System.out.println(e);
}
}