Using Traps and Error Handling

by Dec 10, 2008

Traps are exception handlers that help you catch errors and handle them according to your needs. A Trap statement anywhere in your script:

Trap { 'Something awful happened'} 
1/$null

Whenever an error occurs and an exception is raised, PowerShell executes the script block specified in your script. However, it also will still display its own error message. To avoid that, your trap must handle the error so it will not continue to bubble up and eventually be handled by PowerShell. To handle an exception, add the Continue statement:

Trap { 'Something awful happened'Continue} 
1/$null

Now, PowerShell no longer handles the error rather the exception is handled by your trap. Next, you'd probably like to find out more about the actual error to allow your Trap to handle the error more specifically. Inside your trap, in $_ you have access to the error record:

Trap { "Something awful happened, to be more precise:  $($_.Exception.Message)"Continue} 
1/$null