黑马程序员技术交流社区

标题: 自定义异常 [打印本页]

作者: Aaron9527    时间: 2016-6-2 22:39
标题: 自定义异常
package cn.itcast.自定义异常;
class Student{
        private int age;

        @Override
        public String toString() {
                return "Student [age=" + age + ", getClass()=" + getClass()
                                + ", hashCode()=" + hashCode() + ", toString()="
                                + super.toString() + "]";
        }

        public Student() {
                super();
        }

        /**
         * @return the age
         */
        public int getAge() {
                return age;
        }

        /**
         * @param age the age to set
         */
        public void setAge(int age)throws AgeException {
                if(age>50||age<15){
                        throw new AgeException("您输入的年龄不正确,年龄需要在15~50岁之间!");
                }
                this.age=age;
        }

        public Student(int age) {
                super();
                this.age = age;
        }
       
}
public class Demo {
        public static void main(String[] args) {
                Student list = new Student();
                try {
                        list.setAge(2000);
                } catch (AgeException e) {
                        System.out.println("出现异常了:"+e.getMessage());
                        e.printStackTrace();
                }
                System.out.println(list.getAge());
        }
}











作者: Aaron9527    时间: 2016-6-2 22:40
package cn.itcast.自定义异常;

public class AgeException extends Exception {
        public AgeException(String message){
                super(message);
        }
}





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2