Try Catch vs. Using
Posted by Tihomir Ivanov on 18 February 2009 16:22
Rating: 0.00
Maybe, you wonder which is better choice: "try/catch" or "using" ?
well, it seem that they're really different from each other:
The "using" statement could be useful in:
1. Whenever an exception occurs, the using block takes care of closing connections like database connections, IO connections etc.
2. It also safely disposes the relevant objects
Note*: Only objects that implement IDisposable interface can be used in Using block!
The "try/catch" is used for any error occurred you can catch and display the message to the user.
So, I think the best answer of the question is: Use both of them:
using (OdbcConnection conn = new OdbcConnection(connectionString))
{
try
{
dadapter.SelectCommand.Connection = conn;
OdbcCommandBuilder builder = new OdbcCommandBuilder( dadapter );
conn.Open();
dadapter.Update(dset, "payunit");
}
catch ( Exception ex )
{
// exception handling code.
}
finally
{
conn.Close();
}
} // conn object is disposed.
Comments:
No comments yet.