2014-02-20 49 views
3

我想在Java中使用MySQL来捕捉特定的异常。但是,它正在运行catch (SQLException ex)而不是我想要的那个。发现错误的异常

catch (MySQLIntegrityConstraintViolationException ex) { 
} 
catch (SQLException ex) { 
} 

收到以下错误,我希望它运行catch (MySQLIntegrityConstraintViolationException ex)功能。

11:12:06 AM DAO.UserDAO createUser 
SEVERE: null 
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'idjaisjddiaij123ij' for key 'udid' 

为什么运行catch (SQLException ex)代替catch (MySQLIntegrityConstraintViolationException ex)

+0

你可以添加ex.printStackTrace();在每个catcha里面并粘贴异常? –

+0

它有没有出现在'.getCause()'中? – fge

回答

2

是的MySQL总是在执行方法中捕获SQLException。你所要做的就是赶在你的执行方法的SQLException,他们因此在调用execute方法外方法抛出新MySQLIntegrityConstraintViolationException

public void executeQuery() { 
    try { 
     // code 
     rs = pstmt.executeQuery(); 
} catch (SQLException ex) { 
    throw new MySQLIntegrityConstraintViolationException(ex); 
} 

,它应该只捕获了MySQLIntegrityConstraintViolationException

catch (MySQLIntegrityConstraintViolationException ex) { 
    //handle ex 
} 
+0

即使我遇到过这种情况,萨拉所说的也是我的做法。不知何故,在执行过程中,如果你知道你正在寻找什么异常,然后从SQLException的catch块中抛出它,最终会得到SQLException,这是正确的方法。 –

1

我建议使用ex instanceof MySQLIntegrityConstraintViolationException以确保没有其他异常作为MySQLIntegrityConstraintViolationException抛出,因为可能由于许多不同原因抛出SQLException。

0

请输入

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException; 

我测试,它会工作。

+2

如果没有导入这个类,代码如何编译? – J0e3gan

4

确保您使用正确的名称空间。对于我来说,一个形象附加作品像魅力。

Correct namespace