Java SQLException根据错误代码分开

时间:2015-12-18 23:53:18

标签: java try-catch derby sqlexception

我需要根据using StructureMap.Graph;分隔SQLExceptions。我在ErrorCode中有以下if声明,但始终会打印catch block条件。

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); } 时,会抛出以下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

分隔不同的SQLExceptions

2 个答案:

答案 0 :(得分:1)

---已解决---

首先感谢@blm的路由评论。

特技是; 其他来Exceptions(第1和第2个)的String值只有SQLState ErrorCode个数值SQLException

exception第3链28502 SQLState ErrorCodeExceptions。这是我认为的第一和第二catch (SQLException se) { do { if(se.getSQLState().equals("28502")){ System.out.println("Username Problem"); } else{ System.out.println("Other Problem"); } } while ((se = se.getNextException()) != null); } 之间的区别。

所以我改变了我的

Catch Block;

Other Problem
Other Problem
Username Problem

输出是

$menu = @{}
for ($i=1;$i -lt $List.count; $i++)
{
    Write-Host "  $i. $($List[$i-1].Name)" -foregroundcolor White
    $menu.Add($i,($List[$i-1].Name))
}

答案 1 :(得分:0)

你应该通过使用' getCause()'来获得原因例外。捕获的SqlExeption对象的方法。然后,您可以将结果转换为Exception并检查其错误代码 查看此信息以获取更多信息:Throwable.getCause()

修改

SQLException temp = ex;
while(temp.getCause() != null)
{
     temp = (Exception)temp.getCause();
}
//  check if temp is SQLException and if it is check ((SQLException)temp).getErrorCode() == whatever you want