Let's analyze the following harmless looking line :
---
sqlConn = New SqlConnection(ConfigurationManager.ConnectionStrings
("myDB").ToString)
---
This single line does (atleast) the following:
1. Queries the shared "ConnectionStrings" property of the
ConfigurationManager class which returns a
ConnectionStringSettingsCollection object. This object is a compiled
collection of all loaded connection strings from all loaded
configuration files.
2. It queries the indexer property of this
ConnectionStringSettingsCollection object passing in a string
parameter with the value "myDB". This would return the particular
"ConnectionStringSettings" object matching the provided name.
3. It then invokes an overridden ToString() method on the
ConnectionStringSettings object which basically returns the same thing
as the ConnectionString property. (In addition to what Andrew
mentioned, the latter method makes your intent unambiguous, so should
be used instead). This returns a string value containing the the text
of the connection string as set in the config file.
4. The string retrieved is then passed to the constructor of the
SqlConnection class to create an SqlConnection object.
Does that code still seem trivial? Not to me. I can see any number of
possible pitfalls or places where missing or incorrectly formatted
data could raise an exception. Therefore, the code is deservedly
placed within a Try-catch block. If you are concerned about the
performance implications of exceptions, you can write your code so
that it assumes nothing (the example is probably overkill, but it
illustrates the technique):
---
Dim connStrSettings as ConnectionStringSettings =
ConfigurationManager.ConnectionStrings("myDB")
If connStrSettings isnot Nothing then
Dim connStr as string = connStrSettings.ConnectionString
If Not String.IsNullOrEmpty(connStr) Then
sqlConn = New SqlConnection(connStr)
Try
sqlConn.Open()
...
...
Catch ()
Finally
If sqlConn.State = ConnectionState.Open Then sqlConn.Close()
End Try
Else
'Empty string loaded from Configuration. Log this (fatal) error.
End If
Else
'ConnectionString matching "myDB" not found. Log this (fatal) error.
End If
---
However, a still better way is to use the Using construct (VB 8+):
---
Using (sqlConn = New SqlConnection(connStr))
sqlConn.Open()
...
...
End Using
---
The last point I want to make is that the overhead of an *unhandled*
exception is far greater than that of a gracefully handled one.