一直對java中的throws和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; } }
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; } }