0
    public void onClick() throws SQLException   
  try {
 // Do something
} catch(MySQLIntegrityConstraintViolationException e) { 
     //Can i convert this exception to SQL Exception
}

我可以将 MySQLIntegrityConstraintViolationException 转换为方法抛出的 SQLException 吗?

4

4 回答 4

4

但是 MySQLIntegrityConstraintViolationException 已经一个 SQLExecption (通过继承)!所以没有必要重新抛出它(只需删除 try/catch 块)。

于 2012-09-29T12:18:17.693 回答
3

当然,您可以包装和重新抛出 - 如果您认为它会添加更多信息或使您的想法更普遍。我认为在这种情况下,您捕获的异常提供的信息比您考虑的要多。

不过,我不会选择 SQLException。这是一个检查异常。我认为潮流已经从受检异常转变为不受检异常。

Spring 将 SQLExceptions 包装到扩展 RuntimeException 的未经检查的 DataAccessException 中。我建议你效仿。

这是你应该如何做的:

catch(MySQLIntegrityConstraintViolationException e) { 
    throw new SQLException(e);
}

不要只是传递信息。给出整个堆栈跟踪。

于 2012-09-29T12:16:53.583 回答
1

由于MySQLIntegrityConstraintViolationExceptionSQLException重新抛出的子类是不必要的。如果您想从数据库特定细节中抽象出业务逻辑层,请确保在逻辑层中捕获 SQL 异常,以便即使数据库切换逻辑仍然有效。

于 2012-09-29T12:40:48.953 回答
1

您可以使用构造函数SQLException在您的块中创建一个Catch..

try {
} catch (MySQLIntegrityConstraintViolationException e) {
    throw new SQLException(e);
}
于 2012-09-29T12:19:25.593 回答