1. package com.atguigu.java2;
    2. public class StudentTest {
    3. public static void main(String[] args) {
    4. try {
    5. Student s = new Student();
    6. s.regist(-1001);
    7. System.out.println(s);
    8. } catch (Exception e) {
    9. // e.printStackTrace();
    10. System.out.println(e.getMessage());
    11. }
    12. }
    13. }
    14. class Student{
    15. private int id;
    16. public void regist(int id) throws Exception{
    17. if(id > 0){
    18. this.id = id;
    19. }else{
    20. // System.out.println("您输入的数据非法!");
    21. //手动抛出异常对象
    22. // throw new RuntimeException("您输入的数据非法!");
    23. // throw new Exception("您输入的数据非法!");
    24. throw new MyException("不能输入负数");
    25. }
    26. }
    27. @Override
    28. public String toString() {
    29. return "Student [id=" + id + "]";
    30. }
    31. }
    1. package com.atguigu.java2;
    2. /*
    3. * 如何自定义异常类?
    4. * 1.继承于现有的异常结构:RuntimeException、Exception
    5. * 2.提供全局常量:serialVersionUID
    6. * 3.提供重载的构造器
    7. *
    8. */
    9. public class MyException extends RuntimeException{
    10. static final long serialVersionUID = -7034897193246939L;
    11. public MyException() {
    12. }
    13. public MyException(String msg) {
    14. super(msg);
    15. }
    16. }