I know that Using statement disposes out the object that is being created. Like if I wanted to do something like this:
Using(SqlConnection conn = new SqlConn
There's nothing special about code written inside a using
block - just use a try.catch
to handle exceptions:
using(SqlConnection conn = new SqlConnection(connString))
{
try
{
conn.Open();
// do more stuff here......
}
catch(SqlException sqlEx)
{
// log error and possibly show to user in a MessageBox or something else
}
}
The using(...) { ... }
block itself is designed only to ensure that the resource / object it "encapsulates" is properly disposed of when it's no longer needed. There's is nothing you can do with the using
statement itself to make it handle errors.
So if you expect that just creating the object could fail, then you'd have to put the entire using
block inside the try ... catch
block , or fall back to a try ... catch ... finally
block and ensure proper disposal yourself (as Adam suggested in his answer).