throws和throw抛出异常的使用规则
生活随笔
收集整理的這篇文章主要介紹了
throws和throw抛出异常的使用规则
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一直對java中的throws和throw不太理解。最近一直在查這兩個方面的資料,算是能明白一點吧。如果我下面的觀點哪有不對,希望指出來,我加以改進。
? ?? ? ?throw:(針對對象的做法) ? ?拋出一個異常,可以是系統定義的,也可以是自己定義的。下面舉兩個例子: ? ? 拋出Java中的一個系統異常: public class One { public void yichang(){ NumberFormatException e = new NumberFormatException(); throw e; } public static void main(String[] args){ One test = new One(); try{ test.yichang(); }catch(NumberFormatException e){ System.out.println(e.getMessage()); } } }?
拋出一個自定義的異常: public class People {public static int check(String strage) throws MyException{int age = Integer.parseInt(strage);if(age < 0){throw new MyException("年齡不能為負數!");}return age;}public static void main(String[] args){try{int myage = check("-101");System.out.println(myage);}catch(NumberFormatException e){System.out.println("數據格式錯誤");System.out.println("原因:" + e.getMessage());}catch(MyException e){System.out.println("數據邏輯錯誤");System.out.println("原因:" + e.getMessage());}} } public class MyException extends Exception{private static final long serialVersionUID = 1L;private String name;public MyException(String name){this.name = name;}public String getMessage(){return this.name;} }?
?? throws:(針對一個方法拋出的異常) 拋出一個異常,可以是系統定義的,也可以是自己定義的。 拋出java中的一個系統異常: public class One { public void yichang() throws NumberFormatException{ int a = Integer.parseInt("10L"); } public static void main(String[] args){ One test = new One(); try{ test.yichang(); }catch(NumberFormatException e){ System.out.println(e.getMessage()); } } }?
拋出一個自定義異常: public class People { public static int check(String strage) throws MyException{ int age = Integer.parseInt(strage); if(age < 0){ throw new MyException("年齡不能為負數!"); } return age; } public static void main(String[] args){ try{ int myage = check("-101"); System.out.println(myage); }catch(NumberFormatException e){ System.out.println("數據格式錯誤"); System.out.println("原因:" + e.getMessage()); }catch(MyException e){ System.out.println("數據邏輯錯誤"); System.out.println("原因:" + e.getMessage()); } } }public class MyException extends Exception{ private static final long serialVersionUID = 1L; private String name; public MyException(String name){ this.name = name; } public String getMessage(){ return this.name; } }?
那么下面我要說究竟什么時候用哪種: ? ?如果是系統異常的話可以什么都不用做,也可以針對方法拋出一個異常,因為系統異常是可以被系統自動捕獲的,所以這個異常究竟是要在方法內部解決還是交給上層函數去解決其實效果是一樣的。但是我查了很多資料,即使會拋出異常能被系統所捕獲的話還是建議針對方法寫一個throws,因為這樣在完成一個大型任務的時候可以讓別的程序員知道這里會出現什么異常。 ? 如果是自己定義的異常,則必須要用throws拋出該方法可能拋出的異常,否則編譯會報錯。轉載于:https://www.cnblogs.com/13224ACMer/p/4926106.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的throws和throw抛出异常的使用规则的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 从移动端开发者的角度聊微软的困境和机会
- 下一篇: 对混凝土受扭构件的开裂扭矩可近似采用理想