尝试根据错误代码捕获Java SQLException separate
我需要根据ErrorCode
分隔SQLExceptions
。我在catch block
中有以下if
语句,但是else
条件总是打印出来的
catch (SQLException ex) {
if (ex.getErrorCode() == 28502){
System.out.println("Username Problem");
}
else{
System.out.println("Other Problem");
}
Logger.getLogger(FirstTimeMainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
实际上,当我在创建DB时输入意外的username
时,会抛出以下SQLExceptions
java.sql.SQLException: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XJ041: Failed to create database 'myDB', see the next exception for details.
//rest of exception.
Caused by: ERROR XBM01: Startup failed due to an exception. See next exception for details
//rest of exception.
Caused by: ERROR 28502: The user name 'AAA.AAA' is not valid.
//rest of exception.
但是我的catch
总是打印Other Problem
。如何根据上一个ErrorCode
分隔不同的SQLExceptions
# 1 楼答案
-已解决-
感谢您对@blm first的评论
技巧是其他即将到来的
Exceptions
(第一和第二)在其SQLState
中有String
值,在其ErrorCode
中只有数值SQLException
第三链exception
既有SQLState
又有ErrorCode
。我想这就是第一和第二的区别所以我改变了主意
捕捉块强>
输出为强>
# 2 楼答案
您应该使用捕获的SqlExeption对象的“getCause()”方法获取原因异常。然后,您可以将结果强制转换为异常并检查其错误代码
检查此项以了解更多信息:Throwable.getCause()
编辑: