Traps vs Try/Catch

Traps vs Try/Catch

  • Comments 1

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

Leave a Comment
  • Please add 8 and 5 and type the answer here:
  • Post
  • Which construct handles errors first?  If I throw in a try block, does the catch get the first shot at handling the exception (what I would expect), or does the trap immediately nab it (what I think I'm seeing)?

Page 1 of 1 (1 items)