问题
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