Traps vs Try/Catch

Someone as asking about Traps vs Try/Catch and Jason Shirk (PowerShell developer) gave a nice concise and precise answer that I thought I would share with you:

  • Trap:
    • Designed for admins
    • V1 and V2
    • Introduces a new scope
    • Is “global”, meaning it applies to all code in the same scope, before or after.
    • Does not support rethrow (an empty throw statement throws a special RuntimeException with the message “ScriptHalted”)
  • Try/Catch
    • Designed for developers
    • V2 only
    • Does not introduce a new scope
    • Guarded code is in the try statement block, not the entire scope containing the try statement
    • Supports finally
    • Supports rethrowing exceptions


Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:
Visit the Windows PowerShell ScriptCenter at: