自己定义的Excetpion继承哪个异常有什么讲究?[待解答]

try catch的地方需要用到一个自定义的DBException,如下:

    

于是我就自定义了一个DBException,继承Excetpion,以父类Exception构造器创建构造器:

DBException.java:

 1 package com.tt.bookstore.exception;
 2 
 3 public class DBException extends Exception {
 4 
 5     /**
 6      * 
 7      */
 8     private static final long serialVersionUID = 1L;
 9 
10     public DBException() {
11         super();
12         // TODO Auto-generated constructor stub
13     }
14 
15     public DBException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
16         super(message, cause, enableSuppression, writableStackTrace);
17         // TODO Auto-generated constructor stub
18     }
19 
20     public DBException(String message, Throwable cause) {
21         super(message, cause);
22         // TODO Auto-generated constructor stub
23     }
24 
25     public DBException(String message) {
26         super(message);
27         // TODO Auto-generated constructor stub
28     }
29 
30     public DBException(Throwable cause) {
31         super(cause);
32         // TODO Auto-generated constructor stub
33     }
34 
35     
36     
37 }

这时getConnection()函数里调用DBException处显示异常:

所以将DBException换成继承SQLException,以父类SQLException构造器为构造器:

调用DBException处仍然显示异常,于是改用继承RuntimeException,以父类构造器创建构造器:

此时调用DBException处正常,这引发一个疑惑:自定义的Exception有什么讲究呢?

原文地址:https://www.cnblogs.com/TTTTT/p/6472802.html