Charlie Joynt Charlie Joynt - 4 months ago 10
PowerShell Question

Does it matter where I put a trap{} in my PowerShell script

I have some PowerShell scripts with a load of initialization steps, at the end of which I put a

trap{}
statement, intending to catch all unhandled errors from that point onwards.

Unexpectedly I realized that when I goofed in my initialization logic the
trap{}
was being called even though the error happened before the
trap{}
was defined.

A simple example:

Write-Host "Hello"
Write-Out "World" # Incorrect cmdlet name causes an error

trap{
Write-Warning "Ouch"
return $null
}


Gives:

Hello
WARNING: Ouch


Clearly it seems that it doesn't matter that the
trap{}
is defined after the buggy line of code, but can someone explain why this works anyway?

Answer

From about_Trap:

A script or command can have multiple Trap statements. Trap statements can appear anywhere in the script or command.

You might consider using try/catch/finally if you want more control over which code you want to catch exceptions for.

Comments