throws关键字通常被应用在声明方法时,用来指定可能抛出的异常,多个异常可以使用逗号隔开。仅当抛出了checked 异常,该方法的调用者才必须处理或重新抛出该异常。如果main方法也抛出获取的异常,最终JVM会进行处理,打印异常消息和堆栈信息。
throw关键字通常用在方法体中,并且抛出一个异常对象。程序在执行到throw语句时立即停止,它后面的语句(方法体中)都不执行。
举例说明:
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test(){
- throw new Exception("test");
- }
- }
上面这段程序有问题,有两种修改方案:
一、在test()方法前用throws关键字抛出异常
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test() throws Exception{
- throw new Exception("test");
- }
- }
二、用try/catch语句块将throw new Exception("test");这句包围
- public class Test {
- public static void main(String args[]) {
- try {
- test();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void test() {
- try {
- throw new Exception("test");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }