写出自定义异常类,继承Exception类
实验类TestMyEx.java:
结果:
将regist(100);改为regist(-100);
结果变为:
转载请注明出处!程序猿之洞: http://blog.csdn.net/acmman/
package cn.edu.error; public class MyException extends Exception{ private int id; public MyException(String message,int id){ super(message); this.id=id; } public int getId(){ return this.id; } }
实验类TestMyEx.java:
package cn.edu.error; public class TestMyEx { //<span style="font-family: Arial, Helvetica, sans-serif;">登记</span><span style="font-family: Arial, Helvetica, sans-serif;">学生人数的小程序</span> public void regist(int num) throws MyException{ if(num<0){ throw new MyException("人数为负值,不合理",3); } System.out.println("登记人数"+num); } public void manager(){ try{regist(100);} catch(MyException e){ System.out.println ("登记失败,出错类型码="+e.getId()); e.printStackTrace(); } System.out.println("操作结束"); } public static void main(String[] args) { TestMyEx tme=new TestMyEx(); tme.manager(); } }
结果:
登记人数100 操作结束
将regist(100);改为regist(-100);
结果变为:
登记失败,出错类型码=3 cn.edu.error.MyException: 人数为负值,不合理 at cn.edu.error.TestMyEx.regist(TestMyEx.java:7) at cn.edu.error.TestMyEx.manager(TestMyEx.java:13) at cn.edu.error.TestMyEx.main(TestMyEx.java:23) 操作结束
转载请注明出处!程序猿之洞: http://blog.csdn.net/acmman/