每天写java到期末考试--实验五---异常--6.29

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

    // 默认构造函数,提供默认信息  
    public ScoreException() {
        super("分数异常, 分数应该在0到200之间");
    }
}
Studnet类
// 定义学生类Student
public class Student {
    private String name;
    private int age;
    private double score;

    // 构造方法
    public Student(String name, int age, double score) throws ScoreException {
        this.name = name;
        this.age = age;
        if (score < 0 || score > 200) {
            throw new ScoreException();
        }
        this.score = score;
    }

    // getter和setter方法
    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) throws ScoreException {
        if (score < 0 || score > 200) {
            throw new ScoreException();
        }
        this.score = score;
    }

    // print方法
    public void print() {
        System.out.println("姓名: " + name + ", 年龄: " + age + ", 分数: " + score);
    }
}
Main类
// main方法  
public class Main {
    public static void main(String[] args) {
        try {
            // (1) 创建对象zhangsan,并捕获异常  
            Student zhangsan = new Student("张三", 20, 220);
        } catch (ScoreException e) {
            System.out.println(e.getMessage());
        }

        try {
            // (2) 创建对象lisi,这里不会抛出异常  
            Student lisi = new Student("李四", 30, 120);
            lisi.print(); // 打印信息  

            // (3) 调用lisi的setScore方法给score赋值230,并捕获异常  
            lisi.setScore(230);
        } catch (ScoreException e) {
            System.out.println(e.getMessage());
        }
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值