Handle a terminating error (exception).
Syntax trap [[error_type]] {statement_list} Key error_type The terminating error to trap, requires [brackets]. statement_list A scriptblock of code to be run.
The Trap statement includes a list of statements to run when a terminating error occurs.
By default, this will trap any terminating error or optionally you may specify an error type.
A script or command can have multiple Trap statements. Trap statements can appear anywhere in the script or command.
The common PowerShell option -SilentlyContinue will cause any Throw statement to be completely ignored. This can be mitigated by using Try/Catch or by adding a trap {} statement to trap the error.
Use the Break and Continue keywords in a Trap statement to determine whether a script or command will continue to run after a terminating error.
A Break statement within a Trap statement will stop the function or script:
{ trap {"Error trapped"; break;}
A Continue statement within a Trap statement will resume execution after the statement that caused the error, just as it would without Break or Continue.
{ trap {"Error trapped"; continue;}
A simple trap that will trap any terminating error and display the error by using the $_ automatic variable, in this example we call a non-existent function ('thiswontwork') to force an error:
function TrapTest {
trap {"Error found: $_"}
thiswontwork
}
PS C:\> TrapTest
Error found: The term 'thiswontwork' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included verify that the path is correct, and then try again.The error message above has been edited for brevity.
"When elephant steps on a trap, no more trap” ~ African proverb
Try ... Catch - Handle a terminating error within a scriptblock
about_Try_Catch_Finally