ER-204 Allocation of the resource should follow try/finally pattern to ensure proper de-allocation.

Severity2
Enabledyes
Waivable
RationaleAllocating resource and not properly disposing it is a common problem in applications (JDBC/JNDI/Sockets). Usually this happens due to not using try/finally pattern.
Violation
void problemCode1(DataSource ds)
{
  Connection conn = ds.getConnection();
  PreparedStatement stmt = conn.prepareStatement("SELECT * FROM MY_TABLE");
  //...
  conn.close();
}
		
void problemCode2(DataSource ds)
{
  Connection conn = null;
  try
  {
    Connection conn = ds.getConnection();
    PreparedStatement stmt = conn.prepareStatement("SELECT * FROM MY_TABLE");
    //...
  }
  finally
  {
    conn.close();
  }
}

void problemCode3(DataSource ds)
{
  Connection conn = ds.getConnection();;
  try
  {
    //...
  }
  finally
  {
    
    conn.getAutoCommit(); // can throw an exeption and next line never execute
    conn.close();
    
  }
}
Fix
Connection conn = ds.getConnection();
try
{
  PreparedStatement stmt = conn.prepareStatement("SELECT * FROM MY_TABLE");
	//...
}
finally
{
  conn.close();
}


Hammurapi 3 Copyright © 2004 Hammurapi Group. All Rights Reserved.