throws Exception方法异常处理机制

public class T4 {
    private String sex;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) throws Exception{
        if (sex=="男"||sex=="女"){
            this.sex = sex;
        }else{
            throw new Exception("性别必须为男或者女");
        }

    }

    public static void main(String[] args) {
        T4 t4 = new T4();
        try {
            t4.setSex("00");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("hello");
    }
}

 

2.throw new InputMismatchException
public class T5 {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int sex){
        if (age>1&&age<60){
            this.age = age;
        }else{
            throw new InputMismatchException("年龄必须在1岁和60岁之间");
        }

    }

    public static void main(String[] args) {
        T5 t5 = new T5();
       t5.setAge(80);
        System.out.println("hello");
    }
}

 

posted @ 2017-07-27 16:34  斯丢皮德曼  阅读(1635)  评论(0编辑  收藏  举报