1. 區別
throws是用來聲明一個方法可能拋出的所有異常信息,throws是將異常聲明但是不處理,而是將異常往上傳,誰調用我就交給誰處理。而throw則是指拋出的一個具體的異常類型。
2.分別介紹
throws:用於聲明異常,例如,如果一個方法裡面不想有任何的異常處理,則在沒有任何代碼進行異常處理的時候,必須對這個方法進行聲明有可能產生的所有異常(其實就是,不想自己處理,那就交給別人吧,告訴別人我會出現什麼異常,報自己的錯,讓別人處理去吧)。
格式是:方法名(參數)throws 異常類1,異常類2,.....
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一旦進入被執行,程序立即會轉入異常處理階段,後面的語句就不再執行,而且所在的方法不再返回有意義的值!
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 }