Java自定义异常例题演示

  编写一段程序,完善学生 student 类,增加输入学生的成绩的操作方法,如果小于 0 分或者大于 100 分则抛出异常,并捕捉异常,输出提示信息:输入的学生成绩超出范围了!

import java.util.Scanner;
class MyException extends Exception{
	public MyException(String msg) {
		super(msg);
	}
}
class Student{
	private String name;
	private int age;
	private int score;
	
	public void setScore(int score) throws Exception{
		if(score>0&&score<=100)
			this.score=score;
		else
			throw new MyException("输入的学生成绩超出范围了!");
		
	}
	public String getScore(){
		if(score >= 60)
			return "考试成绩及格";
		else if(score<60&&score!=0)
			return "考试成绩不及格";
		else
			return "成绩输入错误!";
	}
	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 String toString(){
		return ("姓名:" + getName() +",年龄:" + getAge() + ",考试情况:" + getScore());
	}
	
}
public class Experiment {
	
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		Student student = new Student();
		student.setName("小张");
		student.setAge(22);
                System.out.print("输入成绩:");
		int score = sc.nextInt();
		try{
			student.setScore(score);
		}catch(MyException e){
			System.out.println(e.getMessage());
		}
		System.out.println(student);
		System.out.println("*****************");
	}
	
}

运行可能结果:

输入成绩:120
输入的学生成绩超出范围了!
姓名:小张,年龄:22,考试情况:成绩输入错误!
*****************

你可能感兴趣的:(Java)