一个学生类Student该类有学分属性credit整型。2、定义一个获取毕业资格的方法graduate返回布尔值类型方法声明自定义异常CreditException。当学分属性小于最低学分要求45学分时抛出CreditException异常异常信息是学分低于45分。其它返回true。3、在该类的main方法中实例化学生类s学分属性赋值30在异常处理中调用graduate方法在异常处理中输出异常的信
Java代码如下:
class CreditException extends Exception {
public CreditException(String message) {
super(message);
}
}
class Student {
private int credit;
public Student(int credit) {
this.credit = credit;
}
public boolean graduate() throws CreditException {
if (credit < 45) {
throw new CreditException("学分低于45分");
}
return true;
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student(30);
try {
boolean result = s.graduate();
System.out.println(result);
}
catch (CreditException e) {
System.out.println(e.getMessage());
}
}
}
输出结果为:
学分低于45分
``
原文地址: https://www.cveoy.top/t/topic/e9xx 著作权归作者所有。请勿转载和采集!