Java中throws和throw的區別

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.     }  
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章