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