POWERSHELL / CHAPTER 11
Handle failures at the right boundary
AdvancedDistinguish terminating errors, nonterminating errors, and native status.
By the end of this chapter
- Make catchable cmdlet failures explicit
- Use finally for required cleanup
- Inspect native command exit codes separately
The idea
PowerShell distinguishes terminating errors, which interrupt the current operation, from nonterminating errors that may allow processing to continue. Try and catch handle terminating errors. When a cmdlet operation must succeed, -ErrorAction Stop can promote its nonterminating error into one that catch handles. Keep the protected block narrow enough that its recovery policy matches the operations it contains.
Finally provides a cleanup path whether the protected work succeeds or fails. Do not claim success after catching an error unless recovery actually completed. Native programs have exit codes whose interpretation follows that program’s contract; inspect $LASTEXITCODE promptly rather than assuming cmdlet error behavior applies identically. Preserve data and diagnostic channels so callers can distinguish partial output from a fully successful operation.
try {
Write-Error "Invalid sample" -ErrorAction Stop
"unreachable"
} catch {
"handled"
} finally {
"cleanup"
}handled cleanup
ErrorAction Stop makes this error terminating. Catch handles it, the remaining try statement is skipped, and finally still executes.
Try it yourself
Wrap a required read operation with -ErrorAction Stop, report a clear failure, and ensure cleanup runs.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING