繁体   English   中英

在catch块内引发异常

[英]throwing exception inside the catch block

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

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

但是MySQLIntegrityConstraintViolationException已经一个SQLExecption(通过继承)! 因此,无需将其重新抛出(只需删除try / catch-block)。

当然,您可以重新包装-如果您认为这样可以添加更多信息或使您的想法更笼统。 我认为在这种情况下,您正在捕获的异常所提供的信息比您所考虑的要多。

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

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

这是您应该如何做:

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

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

您可以使用SQLException的构造方法在Catch块中创建一个。

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

由于MySQLIntegrityConstraintViolationExceptionSQLException子类,因此不需要抛出。 如果要从数据库特定的详细信息中抽象业务逻辑层,请确保在逻辑层中捕获SQL异常,以便即使交换了数据库逻辑也仍然有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM