PowerShell Throwing Errors
Throwing an error is raising a stopping error with your own message. It stops the current code unless a catch block handles it.
Throw a custom message
Throw stops the code with the message you write. Catch reads that message back.
try { throw "The file name is missing." } catch { "Caught: " + $_.Exception.Message }Throw inside a function
A function can throw, and the caller can catch it. The caller catch runs instead of the function stopping the script.
function Test-Value { param([int]$Number) if ($Number -lt 0) { throw "Number must not be below zero." } "Number is $Number" }
try { Test-Value -Number -3 } catch { "Caught: " + $_.Exception.Message }A good value does not throw
When the value is fine, no error is thrown. The function result prints as normal.
function Test-Value { param([int]$Number) if ($Number -lt 0) { throw "Number must not be below zero." } "Number is $Number" }
Test-Value -Number 4Example
function Test-Value { param([int]$Number) if ($Number -lt 0) { throw "Number must not be below zero." } "Number is $Number" }
try { Test-Value -Number -3 } catch { "Caught: " + $_.Exception.Message }
try { Test-Value -Number 4 } catch { "Caught: " + $_.Exception.Message }Key points
- Throw: the keyword that raises a stopping error with a message you write.
- Custom message: the plain-words reason you give for the error.
- Caught throw: a thrown error handled by a catch block, so the script keeps going.
- Uncaught throw: a thrown error with no catch block, which stops the script.
- Function throw: a throw inside a function that the caller can catch.
In this example, the function throws for a negative number and the first catch prints the message, then the same function returns a normal result for 4.
Note
Throw only for a real problem, not for a normal result.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does throw do when no catch block handles it?