0
我正在使用postgresql jdbc驅動程序,並且存在從SQLException
繼承的類PSQLException
。我應該更好地抓住SQLException
或PSQLException
?在JAVA中捕獲PSQLException
我正在使用postgresql jdbc驅動程序,並且存在從SQLException
繼承的類PSQLException
。我應該更好地抓住SQLException
或PSQLException
?在JAVA中捕獲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
}
}
它與更清晰的異常消息有關。如果你不確定,你可以一個一個使用! – Prashant 2015-04-06 14:10:27