finally

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 of finally is executed before errors are returned, but after the body of catch has executed. This is demonstrated by the following example:

try { 
    Write-Host "Try" 
    throw 'Error' 
} catch { 
    Write-Host "Catch, after Try" 
    throw 
} finally { 
    Write-Host "Finally, after Catch, before the exception" 
} 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.178.106