我们都知道 SQLException 是一个受检异常,并且我们大多数人都同意受检异常是冗长的并且会导致抛出/捕获污染。
我应该选择哪种方法来避免抛出 SQLException?推荐使用哪个包装器/技术/库?(例如 Spring 人员的 DataAccessException,但我不想使用 Spring)
我们都知道 SQLException 是一个受检异常,并且我们大多数人都同意受检异常是冗长的并且会导致抛出/捕获污染。
我应该选择哪种方法来避免抛出 SQLException?推荐使用哪个包装器/技术/库?(例如 Spring 人员的 DataAccessException,但我不想使用 Spring)
只需将其包装为new RuntimeException(jdbce)
. 或者定义您自己的扩展运行时异常的异常并使用它。我认为这里不需要任何框架。甚至 spring 在每次需要时都会通过 unchecked 来包装已检查的异常。
如果您想将已检查的异常视为未检查的异常,您可以这样做
最高可达 Java 7
} catch(SQLException e) {
Thread.currentThread().stop(e);
}
但是在 Java 8 中你可以这样做
/**
* Cast a CheckedException as an unchecked one.
*
* @param throwable to cast
* @param <T> the type of the Throwable
* @return this method will never return a Throwable instance, it will just throw it.
* @throws T the throwable as an unchecked throwable
*/
@SuppressWarnings("unchecked")
public static <T extends Throwable> RuntimeException rethrow(Throwable throwable) throws T {
throw (T) throwable; // rely on vacuous cast
}
并打电话
} catch(SQLException e) {
throw rethrow(e);
}
已检查异常是编译器功能,在运行时不会被区别对待。