Although the ideal is not to capture Exception
by being too generic and throwing the exception again, is not the most appropriate thing to do, yes, it is possible to put the closure of the connection there. It’s just probably not what you want. You want the connection to always be closed, right? If all goes well or an exception is made, the connection must be closed at the end of the process. The language has a standard that ensures this much more simply and effectively:
using (var con = new SqlConnection(connectionString)) {
con.Open();
//algum código aqui....
}
Okay, you’re ensuring closure, you don’t need anything else. The using
will produce a try-finally
calling the dispose()
which will be responsible for closing the connection. Ideally do not try to do in hand, this is the correct form and without risks.
The connection may hang if you do not do so. This applies to any external resource that is acquired. Every time you "open" something needs to ensure that it will be closed the lock is not automatic. This pattern helps achieve this goal in the right way.
In C# 9 can be:
using var con = new SqlConnection(connectionString);
con.Open();
//algum código aqui....
I put in the Github for future reference.
In fact, what I’d like to know is if when an Exception occurs, the connection may or may not be closed because of this Exception error.
– daniel Andrade
And this is answered.
– Maniero