简介
throws 关键字
throws 声明抛出异常的思路是,当前方法不知道如何处理这种类型的异常,该异常应该由上一级调用。 throws 关键字主要用于方法声明上,指的是当方法之中出现异常后交给被调用出处理。 JVM 对异常处理方法是:打印异常的跟踪栈信息,并终止程序运行。
throws 语句的语法格式:
throws ExceptionClass1,ExceptionClass2,ExceptionClass3...
throw 关键字
如果在程序中自行抛出异常,则应该使用 throw 语句,throw 语句可以单独使用,throw 语句抛出的不是异常类,而是一个异常实例,而且每次只能抛出一个实例。
throw 语句的语法格式:
throw ExceptionInstance;
代码实例
throws
当我们的异常在 main() 方法上面抛出了之后,那么就代表这个异常交给了 JVM 处理了,也就是默认的处理机制。
class MyMath {
// 在方法上面抛出异常
public static int div(int x, int y) throws Exception {
return x / y;
}
}
public class Test {
// main 方法上面抛出异常
public static void main(String[] args) throws Exception {
System.out.println("计算结果:" + MyMath.div(10, 2));
}
}
throw
人为自己抛出一个异常。
public class Test {
public static void main(String[] args) {
try {
throw new Exception("自定义异常");
} catch (Exception e) {
e.printStackTrace();
}
}
}
throws 与 throw 的区别
- throw: 指的是在方法中人为的抛出一个异常类对象(这个异常类对象可能是自己实例化或者抛出自己 )
- throws:在方法的声明上使用,表示此方法在调用是必须处理异常。