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
It is a good practice to use the try{}catch(){} inside the using statement if you want to catch an exception thrown by the code inside the using block. Now, consider the following two examples - that explains why try-catch block inside the using statement is a good practice.
Example 1
try{
using(SomeObject so = new SomeObject){
// Perform some tasks
}
}catch(SomeException objSomeException){
// Perform some actions, if exception occurs
}
Example 2
using(SomeObject so = new SomeObject){
try{
// Perform some tasks
}catch(SomeException objSomeException){
// Perform some actions, if exception occurs
}
}
Now, if an exception occurs while performing some tasks inside the using statement, will both example have the same results. The simple answer is no, reason???
When an exception occurs in the example 1, it is caught by the catch block - without reaching the end of the using block. Therefore, the someObject in example 1 will not get disposed properly. Even if CLR is generous (which you should not count on) - the memory used by the someObject in the example 1 will not be recovered (or maximum it will end up in Generation 2 GC collection).
Where in case of the example 2, the catch block is inside the using statement. That means that the execution will reach the end of the using block. Therefore, your object will be disposed and you won't have to worry about the memory leakage (spoilage,