throws是用来声明一个方法可能抛出的所有异常信息,throws是将异常声明但是不处理,而是将异常往上传,谁调用我就交给谁处理
throw是指抛出的一个具体的异常类型
所以throws 是用来声明异常,而 throw 是用来拋出异常!
使用 throws 声明抛出异常的思路是,当前方法不知道如何处理这种类型的异常,该异常应该由向上一级的调用者处理;如果 main 方法也不知道如何处理这种类型的异常,也可以使用 throws 声明抛出异常,该异常将交给 JVM 处理。
- public class Example {
-
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- int result = divide(4,2);
- System.out.println(result);
- }
-
- public static int divide(int x,int y) throws Exception {
- int result = x/y;
- return result;
- }
- }
- public void test(int a,int b) throws ArithmeticException{
- if(b == 0){
- //若b==0,主动抛出异常
- throw new ArithmeticException();
- }else{
- System.out.println(a/b);
- }
- }