I am working on a generic class and am working on handling errors. I am using a try catch on one spot where I am getting an error. The question is, how do I return that error back to the calling method?
public static DataTable GetData(string connString, string sqlStatement, Action<iDB2ParameterCollection> parameters)
{
DataTable dt = new DataTable();
using (iDB2Connection conn = new iDB2Connection(connString))
{
using (iDB2Command cmd = new iDB2Command(sqlStatement, conn))
{
conn.Open();
if (parameters != null) { parameters(cmd.Parameters); }
try
{
using (iDB2DataAdapter da = new iDB2DataAdapter(cmd)) { da.Fill(dt); }
}
catch (iDB2SQLErrorException e)
{
}
conn.Close();
}
}
return dt;
}
We do this, for the same reason you appear to be doing it. So that you can ensure the connection is closed.
We just re-throw the same error and lose the connection in the “finally” block. This lets the connection be closed and still bubble the connection back up to the caller, because the “finally” block gets executed regardless.
The above code is what we’ve used for years, but thanks to the comments, I think it might need tweaking. See this blog post for info on how to preserve the stack trace with exception handling: http://weblogs.asp.net/fmarguerie/archive/2008/01/02/rethrowing-exceptions-and-preserving-the-full-call-stack-trace.aspx