Be Careful With “Throw” Statements (Part 1)

by Feb 12, 2019

Throw is a PowerShell statement that emits an exception to the caller and then exits the code. At least in theory. In the real world, throw might not exit the code, and the results can be devastating.

To understand the problem, take a look at this demo function:

function Copy-Log
{
  "Doing prerequisites"
  "Testing whether target path exists"
  "If target path does not exist, bail out"
  throw "Target path does not exist"
  "Copy log files to target path"
  "Delete log files in original location"
}

When you run Copy-Log, it simulates a fail, assuming a hypothetical target path does not exist. When the target path is not present, log files cannot be copied. When log files cannot be copied, they should not be deleted. That’s why the code needs to exit when throw is called. And it does:

 
PS> Copy-Log
Doing prerequisites
Testing whether target path exists
If target path does not exist, bail out
Target path does not exist
In Zeile:8 Zeichen:3
+   throw "Target path does not exist"
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (Target path does not exist:String) [], RuntimeExceptio 
   n
    + FullyQualifiedErrorId : Target path does not exist

PS> 

However, this is based on the default $ErrorActionPreference value of “Continue”. When a user happens to change this to “SilentlyContinue” in order to suppress error messages, throw suddenly gets completely ignored, and all code executes:

 
PS> $ErrorActionPreference = 'SilentlyContinue'

PS> Copy-Log
Doing prerequisites
Testing whether target path exists
If target path does not exist, bail out
Copy log files to target path
Delete log files in original location

In this scenario, you would have lost all log files because the copy process did not work, yet the code continued and deleted the original files.

Important learning point:

  • If it is important for you to exit a function, throw may not really exit the function. You might want to use a different method to exit your code, for example the “return” statement.

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!