赶上错误的例外 [英] Catching the wrong exception
问题描述
我试图通过 Java
中的 MySQL
来捕获一个特定的异常。但是,它正在运行 catch(SQLException ex)
而不是我想要的那个。
I am trying to catch a specific exception using MySQL
in Java
. However, it is running the catch (SQLException ex)
instead of the one I want it to.
catch (MySQLIntegrityConstraintViolationException ex) {
}
catch (SQLException ex) {
}
获取以下错误,我希望它运行 catch(MySQLIntegrityConstraintViolationException ex)
函数。
Getting the following error, I would expect it to run the catch (MySQLIntegrityConstraintViolationException ex)
function.
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)
?
推荐答案
是 MySQL
始终在执行方法中捕获 SQLException
。你需要做的是在执行方法中捕获 SQLException
,它们会引发新的 MySQLIntegrityConstraintViolationException
Yes MySQL
always thow and catch the SQLException
in the execution method. what you have to do is to catch the SQLException
in your execution method, them throw new MySQLIntegrityConstraintViolationException
public void executeQuery() {
try {
// code
rs = pstmt.executeQuery();
} catch (SQLException ex) {
throw new MySQLIntegrityConstraintViolationException(ex);
}
所以在调用execute方法的外部方法中,应该只捕获 MySQLIntegrityConstraintViolationException
so in the outer method that called the execute method, it should catch only the MySQLIntegrityConstraintViolationException
catch (MySQLIntegrityConstraintViolationException ex) {
//handle ex
}
这篇关于赶上错误的例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!