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