throws异常处理

throwthrows在异常处理中,throw 是人为的抛出异常一般要出现在try{块中}被catch捕获。

throws 一般出现在方法声明之后,表示当前方法中有异常,没有异常处理,进行抛出,如果谁调用此方法,谁就进行处理,如果不处理,则继承在方法上抛出。

①定义一个性别异常类

/**
 * @author victory
 */
public class SexException extends Exception {
    SexException() {
        super("性别设置错误,必须为男或女");
    }

    SexException(String a) {
        super(a);
    }
}

②抛出异常

/**
 * @author victory
 */
public class User {
    /* 自定义异常 ,比如:性别,要么填男 要么填女 不能填abcd.....*/
    private int id;
    private String name;
    private String sex;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) throws SexException {
        if (!"男".equals(sex) && !"女".equals(sex) && !"".equals(sex)) {
            throw new SexException("性别设置异常,必须为男或女或者是空字符串");
        }
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

③测试

/**
 * @author victory
 */
public class UserText {
    public static void main(String[] args) throws SexException {
        User user = new User();
        user.setSex("anis");//anis 不符合性别填写规则,抛出异常
        user.setSex("男");//无异常
        System.out.println(user);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_47827233/article/details/129171466
今日推荐