I got a task to maintain a c# project, I found some code like this:
try{
conn.Open();
...
conn.Close();
}catch(Exception e){
conn.Close();
}
I know that the usual way to close SqlConnection is try-catch-finally or “using” keyword, but I found that I can’t prove the code above is wrong, I can’t find any situation that the Connection will be leak.
So could you give me some technical advises(not programming style) for it?Thanks
You can’t find any situation? What about when that
...code contains areturnstatement? In a loop,continueandbreakcan also fit the bill.Your particular code apparently doesn’t contain any control-flow statements, but that’s beside the point. The point is that when you use the common resource-acquisition idioms, such as try-finally and using, you no longer need to worry about what the rest of the code is. The
...can be one line or a hundred lines; whatever resource you acquired at the top will get released at the bottom if you’ve done it right. Rather than spend time trying to think of other ways that might be right (and having to prove it), use the ways you know are right because they were designed to be right.Besides, even if you can prove that the code never leaks a connection, it’s still a lousy idea for
conn.Close()to be the command that has to solve every possible exception your program could ever throw. Don’t catch exceptions that you don’t know how to resolve.