1、先定义一个类继承Exception和RuntimeException
2、在类中定义一个有参构造
public class MyException extends Exception {
public MyException(String Message) {
super(Message);//输入异常信息
}
}
3、在方法中,在遇到不满足条件的代码里直接用关键字throw抛出异常
一旦你的判断需要做某些异常处理的时候, 你就应该在方法内部用throw关键字把该异常对象抛出。
class Teacher {
public void checkScore(int score) throws MyException{
if (score < 0 || score >100) {
//System.out.println("分数有误");
//异常对象
MyException me = new MyException("分数不在指定范围之内");
throw me;
}else
System.out.println("分数正确");
}
}
public class CheckTest{
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(Exception e) {
System.out.println(e.getMessage());
}
}
}
|
|