PowerShell Traps vs Try/Catch

June 25, 2014 by · Leave a Comment
Filed under: PowerShell 

This post (http://blogs.msdn.com/b/powershell/archive/2009/06/17/traps-vs-try-catch.aspx) gives a great summary of Traps vs Try/Catch as shown below.

  • 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

As a developer I am always looking for new ways to improve my code. Pristine error handling is always a goal with any new code, whether it be PowerShell, C#, or something else. Here are some of the rules I try to follow when developing PowerShell scripts for SharePoint:

DO

  • Use $ErrorActionPreference = “Stop” on all scripts so that exceptions are always caught in the “Catch” block. This line should go in the beginning of the “Try” block. Your “Finally” block should contain $ErrorActionPreference = “Continue”.
  • Use a robust logging capability so that you have a record of the changes made by your scripts. Consider using a separate log just for exceptions or anomalies. This can be hugely helpful when debugging your code.
  • Ensure that your “Catch” blocks are ordered from specific to generic. Look for specific errors first, less specific next, and so on all the way to your most generic.

DON’T

  • Don’t use -ErrorAction SilentlyContinue. While it has its place, it is almost always preferable to catch an error rather than silently continuing past it.
  • Don’t overlook the need for proper exception management in all parts of your code. Doing so can result in difficult to recover changes to your SharePoint farm.