Friday, January 4, 2008

A common no-throw problem in Java and C# samples on the Internet

I guess no-throw is a term used by C++ gurus, but it is also applicable to some Java or .NET applications. for example, I have seen a lot of database connection samples floating on the Internet, unfortunately, most of them are wrong:
here is a example from MSDN: http://msdn2.microsoft.com/en-us/library/ms228366(VS.80).aspx


// Sample C# code accessing a sample database

// You need:
// A database connection
// A command to execute
// A data adapter that understands SQL databases
// A table to hold the result set

namespace DataAccess
{
using System.Data;
using System.Data.SqlClient;

class DataAccess
{
//This is your database connection:
static string connectionString = "Initial Catalog=northwind;Data Source=(local);Integrated Security=SSPI;";
static SqlConnection cn = new SqlConnection(connectionString);

// This is your command to execute:
static string sCommand = "SELECT TOP 10 Lastname FROM Employees ORDER BY EmployeeID";

// This is your data adapter that understands SQL databases:
static SqlDataAdapter da = new SqlDataAdapter(sCommand, cn);

// This is your table to hold the result set:
static DataTable dataTable = new DataTable();

static void Main()
{
try
{
cn.Open();

// Fill the data table with select statement's query results:
int recordsAffected = da.Fill(dataTable);

if (recordsAffected > 0)
{
foreach (DataRow dr in dataTable.Rows)
{
System.Console.WriteLine(dr[0]);
}
}
}
catch (SqlException e)
{
string msg = "";
for (int i=0; i < e.Errors.Count; i++)
{
msg += "Error #" + i + " Message: " + e.Errors[i].Message + "\n";
}
System.Console.WriteLine(msg);
}
finally
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
}
}
}
}
}



Looks like we have covered any possible problem by using try-catch-finally, but there is one place which might give us a surprise, especially in production system:




            finally
{
if (cn.State != ConnectionState.Closed)
{
cn.Close();
}
}



If cn is in a broken state, cn.Close() will throw a Exception, which might be a surprise because nobody is catching it. A better way to make sure the connection resource is released should be:



            finally
{
if (cn.State != ConnectionState.Closed)
{
try{
cn.Close();
}catch (Exception ex)
{
//nothing we can do here, but we don't want a surprise
}
}
}



which looks ugly, but works. Fortunately, C# has a better way to write this, which is correctly documented in SqlConnection online document:

http://msdn2.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx


private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
Console.WriteLine("ServerVersion: {0}", connection.ServerVersion);
Console.WriteLine("State: {0}", connection.State);
}
}


For Java, we are not luckier, a lot of samples have the same problem, you can Google out dozens of them.

In general, it is always a good practice to make sure no-throw in finally block in .NET or Java.

No comments: