Handle a terminating error (exception).

      trap [[error_type]] {statement_list}

   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.


A simple trap that will traps any terminating error displays the error by using the $_ automatic variable:

function TrapTest {
   trap {"Error found: $_"}
C:\PS> 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. 

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;}

"When elephant steps on a trap, no more trap" ~ African proverb

Related PowerShell Cmdlets:

Try ... Catch - Handle a terminating error within a scriptblock

Copyright © 1999-2019
Some rights reserved