How should I wrap a SQLException to an unchecked one?

佐手、 提交于 2019-12-24 03:39:32

问题


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 Spring)


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4375604/how-should-i-wrap-a-sqlexception-to-an-unchecked-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!