public class scorecheak extends Exception{
    public scorecheak(){
    }
    public  scorecheak(String meessage){
        super(meessage);
    }
}
package 自定义异常练习;
public class teach {
    public void cheakscore(int score) throws scorecheak{
    if(score>100||score<0){
        throw new scorecheak("因该输入0~100的数字");
    }else{
        System.out.println("分数正常");}
    }
}
package 自定义异常练习;
import java.util.*;
public class test{
    public static void main(String[] args)  {
        Scanner sc=new Scanner(System.in);
        int score =sc.nextInt();
        teach st=new teach();
        try {
            st.cheakscore(score);
        } catch (scorecheak e) {
            e.printStackTrace();
        }
    }
}
这个程序就是利用自定义异常可以在程序输入的时候利用报错告知哪里出错。

 京公网安备 11010502036488号
京公网安备 11010502036488号