Search code examples
javatry-catchfinally

Throwing exception from within catch and also from finally block


I want to throw any exception that occurs while doing MySQL transaction to the application. But before that I want to close any resources that are in open state. But closing these resources might again generate exception which again I would want to report to application. The following code will make this a little clear:

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
   }   
}

I want to know what is the correct way to handle this situation ( having two exception being thrown ). Thanks for your help.


Solution

  • I suggest you to use Java 7 The try-with-resources Statement

    It's better explained in Oracle Documentation on


    sample code:

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

    Note: A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.