自定义异常类一

自定义异常类

--->extends Exception
--->extends Throwable
都一样

异常类

 1 package com.yeepay.sxf.exception;
 2 /**
 3  * 验证数据格式异常类
 4  * @author sxf
 5  *
 6  */
 7 public class VoaliteDataSimpleException extends Exception{
 8 
 9     /**
10      * 空构造
11      * e.printStackTrace()==>会打印:报错日志信息(类,方法名,行数)
12      * e.getMessage()==>打印:null
13      */
14     public VoaliteDataSimpleException(){
15         super();
16     }
17     
18     /**
19      * 第一种带参数构造
20      * e.printStackTrace()==>会打印:你输入的信息,报错的日志信息(类,方法名,行数)
21      * e.getMessage()==>仅打印:你输入的信息
22      * @param msg
23      */
24     public VoaliteDataSimpleException(String msg){
25         super(msg);
26     }
27     
28     /**
29      * 第二种构造
30      * @param msg
31      * @param cause
32      * e.printStackTrace()==>会打印:你输入的信息,报错的日志信息(类,方法名,行数),Caused By 内容
33      * e.getMessage()==>仅打印:你输入的信息
34      */
35     public VoaliteDataSimpleException(String msg,Throwable cause){
36         super(msg, cause);
37     }
38     
39     /**
40      * 第三种构造
41      * @param cause
42      *  e.printStackTrace()==>会打印:报错的异常类的全路径:你输入的信息,报错的日志信息(类,方法名,行数),Caused By 内容
43      * e.getMessage()==>仅打印:报错的异常类的全路径:你输入的信息
44      */
45     public VoaliteDataSimpleException(Throwable cause){
46         super(cause);
47     }
48 }
View Code

测试类

 1 package com.yeepay.sxf.exception;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         try {
 7             test01();
 8         } catch (VoaliteDataSimpleException e) {
 9             // TODO Auto-generated catch block
10             System.out.println("Test.main()"+e.getMessage());
11             System.out.println("Test.main(ssssssssssssssssssssssssssssssssssssssssssss)");
12             e.printStackTrace();
13         }
14     }
15     public static void test01() throws VoaliteDataSimpleException{
16         int a=0; 
17         int b=2;
18         if(true){
19             throw new VoaliteDataSimpleException(new VoaliteDataSimpleException("数据验证异常"));
20         }
21         
22     }
23 }
View Code

测试结果

Test.main()com.yeepay.sxf.exception.VoaliteDataSimpleException: 数据验证异常
Test.main(ssssssssssssssssssssssssssssssssssssssssssss)
com.yeepay.sxf.exception.VoaliteDataSimpleException: com.yeepay.sxf.exception.VoaliteDataSimpleException: 数据验证异常
    at com.yeepay.sxf.exception.Test.test01(Test.java:21)
    at com.yeepay.sxf.exception.Test.main(Test.java:7)
Caused by: com.yeepay.sxf.exception.VoaliteDataSimpleException: 数据验证异常
    ... 2 more

原文地址:https://www.cnblogs.com/shangxiaofei/p/4740373.html