package com.test;/*** @author shusheng* @description* @Email shusheng@yiji.com* @date 2018/10/10 21:15* * java不可能对所有的情况都考虑到,所以,在实际的开发中,我们可能需要自己定义异常。* 而我们自己随意的写一个类,是不能作为异常类来看的,要想你的类是一个异常类,* 就必须继承自Exception或者RuntimeException* * 两种方式:* A:继承Exception* B:继承RuntimeException
public class MyException extends Exception {public MyException() {}public MyException(String message) {super(message);}}
package com.test;/*** @author shusheng* @description* @Email shusheng@yiji.com* @date 2018/10/10 21:16*/
public class Teacher {// 针对MyException继承自Exception&#xff0c;编译时会检查&#xff0c;未处理的需要抛出public void check(int score) throws MyException {if (score > 100 || score <0) {throw new MyException("分数必须在0-100之间");} else {System.out.println("分数没有问题");}}// 针对MyException继承自RuntimeException&#xff0c;编译时不需要抛出
// public void check(int score) {
// if (score > 100 || score <0) {
// throw new MyException();
// } else {
// System.out.println("分数没有问题");
// }
// }
}
package com.test;import java.util.Scanner;/*** &#64;author shusheng* &#64;description* &#64;Email shusheng&#64;yiji.com* &#64;date 2018/10/10 21:14*/
public class StudentDemo {public static void main(String[] args) {Scanner sc &#61; new Scanner(System.in);System.out.println("请输入学生成绩&#xff1a;");int score &#61; sc.nextInt();Teacher t &#61; new Teacher();try {t.check(score);} catch (MyException e) {e.printStackTrace();}}}