Vimal
Vimal

Reputation: 456

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.

Upvotes: 0

Views: 79

Answers (3)

Braj
Braj

Reputation: 46841

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.

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44813

try

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
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

You may try like this:

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

Upvotes: 1

Related Questions