使用throw抛出年龄异常

Person类代码:

package com.bdqn;

public class Person {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) throws Exception{
        if(age>=1 && age<=100){
            this.age = age;
        }else{
            throw new Exception("年龄必须在1—100之间!");
        }

    }
}

测试类代码:

package com.bdqn;

public class TestAge {
    public static void main(String[] args) {
        Person person = new Person();
        try{
            person.setAge(1231312);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

运行结果:

 

posted @ 2019-02-20 14:16  杨文祥  阅读(789)  评论(0编辑  收藏  举报