之前抛出的均为Exception异常,只能在catch(Exception e){}中被捕获并处理,但由catch(Exception e)捕获到的异常对象包含了Java定义的所有的异常对象。 如果要区分到底是自己抛出的异常还是在Exception中由Java已定义的异常只能由e.toString来识别。 更好的办法是,自定义异常类。
就是由用户自己为可能发生的异常声明为一个异常类,由其对异常进行处理。 自定义的异常类,也需要由catch子句捕获并处理。 自定义的异常类必须是Exception的子类。 以例题说明如何定义及使用,代码中关键部分用注释说明: //此为声明的异常类,此异常用于捕获并处理日期的异常。 //本例捕获由类中抛出的错误,并对其进行处理 //本例的处理很简单,仅输出其错误 public class DateFormatException extends Exception{ public DateFormatException(){ System.out.println("wowo"); } public DateFormatException(Strings){ if(s.equals("年份错误"))//如果年份错误,如何处理 System.out.println("年份错误,请重新输入年份"); if(s.equals("月份错误"))//如果月份错误,如何处理 System.out.println("月份错误,请重新输入月份"); if(s.equals("天数错误"))//如果天数错误,如何处理 System.out.println("天数错误,请重新输入天数"); } } //此类用来辅助学习自定义异常类 public class erro { private int year,month,day; public erro(){ this(1986,1,1); } public erro(int year,int month,int day){ this.year=year; this.month=month; this.day=day; } //set方法要抛出异常,抛出的异常会被类 DateFormatException接收并处理 public void set(int year,int month,int day) throws DateFormatException { if(year<0||year>2018) thrownew DateFormatException("年份错误");//抛出异常,会调用DateFormatException中带参的构造函数 else this.year=year; if(month<0||month>12) throw new DateFormatException("月份错误");//抛出异常,会调用DateFormatException中带参的构造函数 else this.month=month; if(day<0||day>31) throw new DateFormatException("天数错误");//抛出异常,会调用DateFormatException中带参的构造函数 else this.day=day; } public static void main(String args[]){ erro ab=new erro(); try{ ab.set(2500,12,25);//年份大于规定年份,会出错 } catch(Exception e){ } try{ ab.set(2000,15,25);//月份大于规定年份,会出错 } catch(Exception e){ } try{ ab.set(2000,12,55);//天数大于规定年份,会出错 } catch(Exception e){ } finally{ System.out.println("Congratuations,zxx"); } } } 其运行结果如下: 年份错误,请重新输入年份 月份错误,请重新输入月份 天数错误,请重新输入天数 Congratuations,zxx |
|
来自: pythonjava学习 > 《待分类》