Terminating errors

Terminating errors can be generated on demand, or by setting the ErrorActionPreference for the entire session to Stop. Terminating errors need to be handled in your code; otherwise, they will also terminate your script. Hence, the name. The usual error handling is done with a try/catch block. We try to execute a cmdlet, catch any exception, and, finally, do a cleanup task that is always executed, even if no exception has been thrown:

try
{
$items = Get-Item -Path C:DoesNotExist, C:Windows, $env:APPDATA -ErrorAction Stop
}
catch [System.Management.Automation.ItemNotFoundException]
{
# Specific catch block for the exception type
# PSItem contains the error record, and TargetObject may contain the actual object raising the error
Write-Host ('Could not find folder {0}' -f $PSItem.TargetObject)
}
finally
{
# Regardless of whether an error occurred or not, the optional
# finally block is always executed.
Write-Host 'Always executed'
}

You can find out which type of exception occurred by examining its type, using $Error[0].Exception.GetType().FullName.

Another approach that you should try not to take is trapping the error. This is usually done during development, when it is not yet clear what kinds of unhandled exceptions can occur. A trap block catches all unhandled exceptions, and can be used to gracefully exit a script or just to log the exception:

# Trapping errors
# At the beginning of a script, a trap can be introduced to trap any terminating errors that
# are not handled.
trap
{
Write-Host ('Could not find folder {0}' -f $PSItem.TargetObject)
continue # or break
}

# Will not trigger the trap
$items = Get-Item -Path C:DoesNotExist, C:Windows, $env:APPDATA

# Will trigger the trap
$items = Get-Item -Path C:DoesNotExist, C:Windows, $env:APPDATA -ErrorAction Stop

# Additional code runs if trap statement uses continue
Write-Host 'This is not a good idea'

You can find trap blocks at the beginning of a script. The main reason to not use traps is that you cannot properly control the code flow after an exception has been caught. Maybe the exception is something that you should handle in the code because it can be corrected (such as a missing folder). Maybe the exception should really terminate your script, as you cannot recover from it, and it will break the rest of the script.

..................Content has been hidden....................

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