MyBatis 的異常模塊,源碼對應exceptions
包。異常模塊雖然不屬於基礎支持層,可是也貫穿了業務處理的各個環節。以下圖: java
IbatisException
已經被廢棄。 org.apache.ibatis.exceptions.PersistenceException
是MyBatis真正的異常基類。代碼以下:apache
@Deprecated
public class IbatisException extends RuntimeException {
....省略代碼
}
public class PersistenceException extends IbatisException {
private static final long serialVersionUID = -7537395265357977271L;
public PersistenceException() {
super();
}
public PersistenceException(String message) {
super(message);
}
public PersistenceException(String message, Throwable cause) {
super(message, cause);
}
public PersistenceException(Throwable cause) {
super(cause);
}
}
複製代碼
org.apache.ibatis.exceptions.TooManyResultsException
繼承 PersistenceException類,查詢返回結果過多的異常:指望返回一條,實際返回了多條。代碼以下:session
public class TooManyResultsException extends PersistenceException {
private static final long serialVersionUID = 8935197089745865786L;
public TooManyResultsException() {
super();
}
public TooManyResultsException(String message) {
super(message);
}
public TooManyResultsException(String message, Throwable cause) {
super(message, cause);
}
public TooManyResultsException(Throwable cause) {
super(cause);
}
}
複製代碼
org.apache.ibatis.exceptions.ExceptionFactory
異常工廠,用於包裝異常成PersistenceException
。代碼以下:ui
public class ExceptionFactory {
private ExceptionFactory() {}
/** * 包裝異常成 PersistenceException * @param message 消息 * @param e 發生的異常 * @return PersistenceException */
public static RuntimeException wrapException(String message, Exception e) {
return new PersistenceException(ErrorContext.instance().message(message).cause(e).toString(), e);
}
}
複製代碼
實際上,咱們會看到各個模塊包下面都有其都有的異常類,代碼大部分都是相同的,繼承,代碼以下:spa
public class BindingException extends PersistenceException {
private static final long serialVersionUID = 4300802238789381562L;
public BindingException() {
super();
}
public BindingException(String message) {
super(message);
}
public BindingException(String message, Throwable cause) {
super(message, cause);
}
public BindingException(Throwable cause) {
super(cause);
}
}
複製代碼
簡單整理下:code
Java雖然提供了豐富的異常處理類,可是在項目中還會常用自定義異常,其主要緣由是Java提供的異常類在某些狀況下仍是不能知足實際需球。例如如下狀況:cdn
失控的阿甘,樂於分享,記錄點滴blog