Java 如何自定义异常类

 1 package com.bytezero.throwable;
 2 
 3 /**
 4  * 
 5  * @Description      如何自定义异常类
 6  * @author Bytezero·zhenglei!        Email:420498246@qq.com
 7  * @version
 8  * @date 上午8:41:17
 9  * @  1.继承于现有的异常结构:RuntimeException  Exception
10  *    2.提供全局常量: serialVersionUID
11  *    3.提供 重载的构造器
12  *    
13  *    
14  */
15 public class MyException extends Exception {
16 
17      static final long serialVersionUID = -7034897190745766939L;
18      
19      public MyException() {
20          
21      }
22      
23      public MyException(String msg) {
24          super(msg);
25          
26      }
27 }
 1 package com.bytezero.throwable;
 2 
 3 public class StudentsTest {
 4 
 5     public static void main(String[] args) {
 6         try {
 7             Student s = new Student();
 8             s.regist(-1001);
 9             System.out.println(s);
10         }catch(Exception e){
11 //            e.printStackTrace();
12             System.out.println(e.getMessage());
13         }
14     }
15 }
16 
17 class Student{
18     
19     int id;
20     
21     public void regist(int id) throws Exception {
22         
23         if(id > 0) {
24             
25             this.id = id;
26         }else {
27             //System.out.println("您输入的数据非法!");
28             
29             //手动抛出异常
30             //throw new RuntimeException("您输入的数据非法!");
31             //throw new Exception("您输入的数据非法!");
32             throw new MyException("数据非法-----自定义异常类"); 
33         }
34         
35     }
36 
37     @Override
38     public String toString() {
39         return "Student [id=" + id + "]";
40     }
41     
42     
43     
44     
45 }

 

posted on 2021-10-10 08:55  Bytezero!  阅读(156)  评论(0编辑  收藏  举报