从catch内部以及finally块中抛出异常

时间:2014-08-21 08:51:16

标签: java try-catch finally

我想抛出在对应用程序执行MySQL事务时发生的任何异常。但在此之前,我想关闭所有处于开放状态的资源。但关闭这些资源可能会再次产生异常,我再次想要向应用程序报告。 以下代码将使这一点变得清晰:

try
{
   // connect to MySQL DB using JDBC and run different queries
}
catch ( Exception e )
{
   // throw this exception by wrapping it in another user defined exception class
}
finally
{
   try
   {
      // close resources opened in try block ( statement, connection )
   }
   catch ( Exception e )
   {
      // throw this exception by wrapping it in another user defined exception class
   }   
}

我想知道处理这种情况的正确方法是什么(抛出两个异常)。 谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

您可以尝试这样:

try
{
   // connect to MySQL DB using JDBC and run different queries
}
catch ( Exception e )
{
   // throw this exception by wrapping it in another user defined exception class
}
finally
{
  closeMyConnection(resource);
}

protected void closeMyConnection( Resource resource ) {
  try {
    if (resource != null) {
      resource.close();
    }
  } catch( Exception ex ) {
    log( "There is some excetion", ex );
  }
}

答案 1 :(得分:1)

我建议您使用Java 7 The try-with-resources Statement

中的 Oracle文档中有更好的解释

示例代码:

try(  Connection conn = dataSource.getConnection();
      PreparedStatement stmt = conn.prepareStatement(query);
      ResultSet rs = stmt.executeQuery() ) {
     // connection, statements and result set are automatically closed 
}

注意: try-with-resources 语句可以拥有catchfinally块,就像普通的try语句一样。在 try-with-resources 语句中,任何catchfinally块在声明的资源已经关闭后运行。

答案 2 :(得分:1)

Exception lastException = null:
try
{
   // connect to MySQL DB using JDBC and run different queries
}
catch ( Exception e )
{
   // throw this exception by wrapping it in another user defined exception class
   lastException = e;
}

if (lastException != null) {
  // you know what to do
}