throw和throws作为Java中两种异常抛出关键字,虽然两个长的很像,但是却有着很大的区别。
区别1:
throws:
跟在方法声明后面,后面跟的是异常类名
throw:
用在方法体内,后面跟的是异常类对象名
public static void method() throws ArithmeticException {// 跟在方法声明后面,后面跟的是异常类名
int a=10;
int b=0;
if(b==0) {
throw new ArithmeticException();用在方法体内,后面跟的是异常类对象名
}else {
System.out.println(a/b);
}
}
}
区别2:
throws:
可以跟多个异常类名,用逗号隔开
throw:
只能抛出一个异常对象名
public static void method() throws ArithmeticException,Exception {//跟多个异常类名,用逗号隔开
int a=10;
int b=0;
if(b==0) {
throw new ArithmeticException();// 只能抛出一个异常对象名
}else {
System.out.println(a/b);
}
}
}
区别3:
throws:
表示抛出异常,由该方法的调用者来处理
throw:
表示抛出异常,由该方法体内的语句来处理
public class throwandthrows {
public static void main(String[] args) {
try {
method();//由该方法的调用者来处理
}catch (ArithmeticException e) {
e.printStackTrace();
}
}
public static void method() throws ArithmeticException {
int a=10;
int b=0;
if(b==0) {
throw new ArithmeticException();//由该方法体内的语句来处理
}else {
System.out.println(a/b);
}
}
}
区别4:
throws:
throws表示有出现异常的可能性,并不一定出现这些异常
throw:
throw则是抛出了异常,执行throw一定出现了某种异常
我们向上面例子代码里throws一个IndexOutOfBoundsException异常,编译发现并没有报错,这就体现了throws表示有出现异常的可能性
public class throwandthrows {
public static void main(String[] args) {
try {
method();
}catch (ArithmeticException e) {
e.printStackTrace();
}
}
public static void method() throws ArithmeticException,IndexOutOfBoundsException {
int a=10;
int b=0;
if(b==0) {
throw new ArithmeticException();
}else {
System.out.println(a/b);
}
}
}