自定义异常

 1 package com.fu.java5;
 2 
 3 /**
 4  * 如何自定义异常类
 5  * 1.继承现有的异常结构:RuntimeException、Exception
 6  * 2.提供全局常量:serialVersionUID;
 7  * 3.提供重载的构造器
 8  *
 9  *
10  */
11 public class MyException extends RuntimeException{
12 
13     static final long serialVersionUID = -70971907766939L;
14 
15     public MyException(){
16 
17     }
18     public MyException(String msg){
19         super(msg);
20     }
21 }

 

 1 package com.fu.java5;
 2 
 3 /**
 4  * 手动抛出异常的测试
 5  *
 6  *
 7  */
 8 public class StudentTest {
 9     public static void main(String[] args) {
10         try {
11             Student s = new Student();
12             s.regist(-1001);
13             System.out.println(s);
14         } catch (Exception e) {
15 //            e.printStackTrace();
16             System.out.println(e.getMessage());
17         }
18     }
19 }
20 
21 class Student{
22     int id;
23     public void regist(int id) throws Exception {
24         if(id > 0){
25             this.id = id;
26         }else {
27 //            System.out.println("您输入的数据非法!");
28             //手动抛出异常
29             throw new Exception("您输入的数据非法!");
30         }
31     }
32 
33     @Override
34     public String toString() {
35         return "Student{" +
36                 "id=" + id +
37                 '}';
38     }
39 }

 

posted @ 2021-10-05 14:58  橘猫的夏天  阅读(13)  评论(0编辑  收藏  举报