February 2019
Intermediate to advanced
626 pages
15h 51m
English
The finally block will invoke whether an error is thrown or not. This makes it ideal for handling situations where things must always be cleanly closed down.
The following function ignores errors, but will always close down an open SQL connection, whether the ExecuteReader method succeeds or not:
using namespace System.Data.SqlClient
$connectionString = 'Data Source=dbServer;Initial Catalog=dbName'
try {
$sqlConnection = [SqlConnection]::new($connectionString)
$sqlConnection.Open()
$sqlCommand = $sqlConnection.CreateCommand()
$sqlCommand.CommandText = 'SELECT * FROM Employee'
$reader = $sqlCommand.ExecuteReader()
} finally {
if ($sqlConnection.State -eq 'Open') {
$sqlConnection.Close()
}
}
When catch is used with finally, the content ...
Read now
Unlock full access