首页 > 解决方案 > 从 SQLException 异常中获取 SQLState

问题描述

我有抛出包装在 RuntimeException 中的 SQLException 的代码,例如:

} catch (RuntimeException e) {
        Throwable t = e.getCause();
        
while ((t != null) && !(t instanceof java.sql.SQLException)) {
t = t.getCause();
}
 . . . Someother code
if (SQLState==) {
//throw new custom exception based on  SQLState);
}

如何在 if 循环中获取 SQLState?不知何故,while循环t为空。

标签: javaexceptionjdbcruntimeexceptionsqlexception

解决方案


得到了答案

        } catch (RuntimeException e) {
        Throwable t = e.getCause();
        SQLException exp;
        while ((t != null) && !(t instanceof SQLException)) {
            t = t.getCause();
            exp= (SQLException) t;  
        }
        if (exp.getSQLState=="....")) {
             throw new custom exception based on  SQLState); 
        }
    }

推荐阅读