Traps vs Try/Catch

PowerShell Team

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

Enjoy!

Jeffrey Snover [MSFT]
Distinguished Engineer
Visit the Windows PowerShell Team blog at:    http://blogs.msdn.com/PowerShell
Visit the Windows PowerShell ScriptCenter at:  http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspx

0 comments

Discussion is closed.

Feedback usabilla icon