java_自定义异常

自定义异常格式:

public class 异常类名 extends Exception {
    无参构造
    带参构造
}

实例:

首先自定义一个分数异常类 ScoreException

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

然后创建一个Teacher类 继承 ScoreException类

public class Teacher {
    public void checkScore(int score) throws ScoreException {
        if(score>=0&&score<=100) {
            System.out.println("分数正常");
        }else{
//            throw new ScoreException(); //
            throw new ScoreException("分数输入有误,应在0-100之间!");
        }
    }
}

然后验证自定义异常是否正确

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();
//        t.checkScore(score); // Alt + Enter 选择 try/catch 选项
        try {
            t.checkScore(score);
        } catch (ScoreException e) {
            e.printStackTrace();
        }
    }
}

 

你可能感兴趣的:(Java_基础02_04)