【发布时间】:2015-04-06 13:50:16
【问题描述】:
我正在使用 postgresql jdbc 驱动程序,并且有类 PSQLException 继承自 SQLException。我应该更好地捕捉SQLException 或PSQLException?
【问题讨论】:
-
与更清晰的异常信息有关。不确定的可以一一使用!!
我正在使用 postgresql jdbc 驱动程序,并且有类 PSQLException 继承自 SQLException。我应该更好地捕捉SQLException 或PSQLException?
【问题讨论】:
如果您真的想捕获异常,以便您的方法将处理异常并且不需要在其throws 子句中声明SQLException,那么您将需要捕获SQLException。这是因为 JDBC API 声明抛出 SQL 异常。
大部分PSQLExceptions 无论如何我们都会包裹在更通用的SQLException 中,因此要访问它们,您可能会使用以下内容:
public static <T> T unwrapCause(Class<T> clazz, Throwable e) {
while (!clazz.isInstance(e) && e.getCause() != null && e != e.getCause()) {
e = e.getCause();
}
return clazz.isInstance(e) ? clazz.cast(e) : null;
}
然后在您的代码中,您会得到这样的PSQLException:
} catch (SQLException e) {
PSQLException psqle = unwrapCause(PSQLException.class, e);
if (psqle != null) {
... // handling of the PostgreSQL specific exception
}
}
【讨论】: