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,不符合要求"); } } }