标签:
一直对java中的throws和throw不太理解。最近一直在查这两个方面的资料,算是能明白一点吧。如果我下面的观点哪有不对,希望指出来,我加以改进。
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; } }
标签:
原文地址:http://www.cnblogs.com/13224ACMer/p/4926106.html