
范例:
package _4._219;
public class ScoreException extends Exception{
public ScoreException() {
}
public ScoreException(String message) {
super(message);
}
}

练习程序:老师输入成绩
ScoreException
package _4._219;
public class ScoreException extends Exception{
public ScoreException() {
}
public ScoreException(String message) {
super(message);
}
}
Teacher:老师对象,检查分数方法
package _4._219;
public class Teacher {
public void checkScore(int score) throws ScoreException {
if (0>score||100<score){
// throw new ScoreException();
throw new ScoreException("输入数字大小异常");
}else {
System.out.println("输入正常");
}
}
}
TeacherTest
package _4._219;
import java.util.Scanner;
public class TeacherTest {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入分数");
int score=sc.nextInt();
Teacher t=new Teacher();//定义一个老师对象
try{
t.checkScore(score);//使用老师对象的方法
}catch (ScoreException e){
e.printStackTrace();
}
}
}
该程序演示了如何在Java中处理异常,特别是当老师检查输入的成绩时。如果分数超出0到100的范围,程序会抛出一个`ScoreException`,附带错误消息。在`TeacherTest`类中,通过`try-catch`块捕获并打印异常堆栈跟踪。
4986

被折叠的 条评论
为什么被折叠?



