开发者

How should I wrap a SQLException to an unchecked one?

We all know that SQLException is a checked Exception and most of us agree that checked Exception are verbose and leads to throw/catch pollution.

Which approach should I choose to avoid SQLException throwing? Which wrapper/technique/library is recommended? (for example DataAccessException for the Spring folks, but I don't want to use 开发者_StackOverflowSpring)


Just wrap it as new RuntimeException(jdbce). Or defince your own exception that extends runtime exception and use it. I do not think that any framework is required here. Even spring wraps checked exceptions by unchecked every time it needs it.


If you want to treat a checked exception as an unchecked one, you can do

Up to Java 7 you can do

} catch(SQLException e) {
   Thread.currentThread().stop(e);
}

However in Java 8 you can do

/**
 * 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
}

and call

} catch(SQLException e) {
   throw rethrow(e);
}

Checked exceptions are a compiler feature and are not treated differently at runtime.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜