1. 區別
throws是用來聲明一個方法可能拋出的所有異常資訊,而throw則是指拋出的一個具體的異常類型。此外throws是將異常聲明但是不處理,而是將異常往上傳,誰調用我就交給誰處理。
2.分別介紹
throws:用於聲明異常,例如,如果一個方法裡面不想有任何的異常處理,則在沒有任何代碼進行異常處理的時候,必須對這個方法進行聲明有可能產生的所有異常(其實就是,不想自己處理,那就交給別人吧,告訴別人我會出現什麼異常,報自己的錯,讓別人處理去吧)。
格式是:方法名(參數)throws 異常類1,異常類2,.....
Java代碼
- class Math{
- public int div(int i,int j) throws Exception{
- int t=i/j;
- return t;
- }
- }
-
- public class ThrowsDemo {
- public static void main(String args[]) throws Exception{
- Math m=new Math();
- System.out.println("出發操作:"+m.div(10,2));
- }
- }
throw:就是自己進行異常處理,處理的時候有兩種方式,要麼自己捕獲異常(也就是try catch進行捕捉),要麼聲明拋出一個異常(就是throws 異常~~)。注意:throw一旦進入被執行,程式立即會轉入異常處理階段,後面的語句就不再執行,而且所在的方法不再返回有意義的值!
Java代碼
- public class TestThrow
- {
- public static void main(String[] args)
- {
- try
- {
- //調用帶throws聲明的方法,必須顯式捕獲該異常
- //否則,必須在main方法中再次聲明拋出
- throwChecked(-3);
- }
- catch (Exception e)
- {
- System.out.println(e.getMessage());
- }
- //調用拋出Runtime異常的方法既可以顯式捕獲該異常,
- //也可不理會該異常
- throwRuntime(3);
- }
- public static void throwChecked(int a)throws Exception
- {
- if (a > 0)
- {
- //自行拋出Exception異常
- //該代碼必須處於try塊裡,或處於帶throws聲明的方法中
- throw new Exception("a的值大於0,不符合要求");
- }
- }
- public static void throwRuntime(int a)
- {
- if (a > 0)
- {
- //自行拋出RuntimeException異常,既可以顯式捕獲該異常
- //也可完全不理會該異常,把該異常交給該方法調用者處理
- throw new RuntimeException("a的值大於0,不符合要求");
- }
- }
- }