2016-06-30
1 创建自己的异常类
1、继承Throwable
2、继承Exception
修饰符 class 类名 extends Exception{
//类体
}
package com.java1995; /** * 定义自己的异常类 * @author Administrator * */ public class TestException { public static void main(String[] args) { MyException me=new MyException("自己的异常类"); System.out.println(me.getMessage()); System.out.println(me.toString()); } } class MyException extends Exception{ public MyException(){ } public MyException(String msg){ super(msg); } }
2 使用自己的异常类
自己定义的异常一般用于throw
package com.java1995; /** * 调用自己的异常 * @author Administrator * */ public class AgeTest { public static void main(String[] args) { try { ageLevel(1000); } catch (IllegalAgeException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static String ageLevel(int age) throws IllegalAgeException{ if(age>= 10&& age<18){ return "少年"; } else if(age>18&&age<=30){ return "青年"; }else if(age>30&&age<=60){ return "中年"; }else if(age>60&&age<=120){ return "老年"; }else{ //抛出异常 throw new IllegalAgeException("非法的年龄!!!"); } } } /** * 定义自己的异常类 * @author Administrator * */ class IllegalAgeException extends Exception{ public IllegalAgeException(String msg){ super(msg); } }
【参考资料】