java異常處理的throw和throws的區別

來源:互聯網
上載者:User

1. 區別

 

throws是用來聲明一個方法可能拋出的所有異常資訊,而throw則是指拋出的一個具體的異常類型。此外throws是將異常聲明但是不處理,而是將異常往上傳,誰調用我就交給誰處理。

2.分別介紹

  throws:用於聲明異常,例如,如果一個方法裡面不想有任何的異常處理,則在沒有任何代碼進行異常處理的時候,必須對這個方法進行聲明有可能產生的所有異常(其實就是,不想自己處理,那就交給別人吧,告訴別人我會出現什麼異常,報自己的錯,讓別人處理去吧)。

格式是:方法名(參數)throws 異常類1,異常類2,.....

 

 

Java代碼  
  1. class Math{  
  2.       public int div(int i,int j) throws Exception{  
  3.           int t=i/j;  
  4.           return t;  
  5.       }  
  6.  }  
  7.   
  8. public class ThrowsDemo {  
  9.       public static void main(String args[]) throws Exception{  
  10.           Math m=new Math();  
  11.           System.out.println("出發操作:"+m.div(10,2));  
  12.      }  
  13.  }  

throw:就是自己進行異常處理,處理的時候有兩種方式,要麼自己捕獲異常(也就是try catch進行捕捉),要麼聲明拋出一個異常(就是throws 異常~~)。注意:throw一旦進入被執行,程式立即會轉入異常處理階段,後面的語句就不再執行,而且所在的方法不再返回有意義的值!

 

Java代碼  
  1. public class TestThrow  
  2. {  
  3.     public static void main(String[] args)   
  4.     {  
  5.         try  
  6.         {  
  7.             //調用帶throws聲明的方法,必須顯式捕獲該異常  
  8.             //否則,必須在main方法中再次聲明拋出  
  9.             throwChecked(-3);             
  10.         }  
  11.         catch (Exception e)  
  12.         {  
  13.             System.out.println(e.getMessage());  
  14.         }  
  15.         //調用拋出Runtime異常的方法既可以顯式捕獲該異常,  
  16.         //也可不理會該異常  
  17.         throwRuntime(3);  
  18.     }  
  19.     public static void throwChecked(int a)throws Exception  
  20.     {  
  21.         if (a > 0)  
  22.         {  
  23.             //自行拋出Exception異常  
  24.             //該代碼必須處於try塊裡,或處於帶throws聲明的方法中  
  25.             throw new Exception("a的值大於0,不符合要求");  
  26.         }  
  27.     }  
  28.     public static void throwRuntime(int a)  
  29.     {  
  30.         if (a > 0)  
  31.         {  
  32.             //自行拋出RuntimeException異常,既可以顯式捕獲該異常  
  33.             //也可完全不理會該異常,把該異常交給該方法調用者處理  
  34.             throw new RuntimeException("a的值大於0,不符合要求");  
  35.         }  
  36.     }  
  37. }  

   

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.