uncheckException的處理
class User{ PRivate int age; public void setAge(int age){ if(age < 0){ //生成異常對象 RuntimeException e = new RuntimeException("年齡不能為負數"); throw e; //終止運行,拋出異常對象 } this.age = age; }}class Test{ public static void main(String args[]){ User u = new User(); u.setAge(-20); }}
JVM不能識別的異常,比如年齡為負數,在語法上沒有錯誤但不符合實際,需要靠人為識別異常,生成異常對象,通過throw拋出異常。JVM得到異常對象后則終止代碼運行。
checkException的處理
class User{ private int age; public void setAge(int age){ if(age < 0){ Exception e = new Exception("年齡不能為負數"); throw e; } this.age = age; }}
捕獲:使用try…catch…finally
聲明:使用throws
當setAge方法有可能產生checkException時,如Exception類型的異常,在函數后面添加throws聲明Exception這樣的異常對象,產生異常后由調用setAge方法的地方來處理。
class User{ private int age; public void setAge(int age) throws Exception{ if(age < 0){ Exception e = new Exception("年齡不能為負數"); throw e; } this.age = age; }}再次編譯Test.java時提示如下錯誤:

class Test{public static void main(String args[]){User u = new User();try{u.setAge(-20);}catch(Exception e){e.printStackTrace();}}}
當在User類中的setAge方法后通過throws聲明異常類型后,Test主函數中調用了setAge方法產生了異常并用try…catch進行處理。
總結:
Throw的作用:JVM無法判斷的異常,可通過生成異常對象用thorw拋出異常
Throws的作用:用來聲明一個函數可能會產生異常,函數不對異常進行處理,調用函數的地方對異常進行處理。
參考:http://dev.yesky.com/61/8111561.shtml#top
新聞熱點
疑難解答