Terminating vs. Non‑Terminating Errors¶
PowerShell has two categories of errors: terminating and non‑terminating.
Understanding the difference is essential for writing predictable scripts and controlling how your code reacts when something goes wrong.
1. Non‑Terminating Errors¶
A non‑terminating error reports a problem but allows the script to continue running.
These errors occur when PowerShell encounters an issue that is serious enough to warn the user, but not serious enough to stop execution.
Most cmdlets produce non‑terminating errors by default.
Example: trying to delete a file that doesn’t exist¶
Remove-Item "C:\NoSuchFile.txt"
Output:
Remove-Item : Cannot find path 'C:\NoSuchFile.txt' because it does not exist.
But the script keeps running after this error.
Why non‑terminating errors exist¶
They are useful when:
- You want to process many items
- Some items may fail
- You still want to continue with the rest
For example, deleting 100 files should not stop because 1 file is missing.
2. Terminating Errors¶
A terminating error stops execution immediately.
PowerShell halts the current pipeline, function, or script unless the error is caught with try/catch.
Terminating errors occur when:
- PowerShell cannot continue safely
- A cmdlet is configured to treat the error as fatal
- You explicitly force a terminating error
Example: calling a nonexistent command¶
NoSuchCommand
This produces a terminating error because PowerShell cannot continue.
Example: forcing a terminating error¶
throw "Something went wrong."
This stops execution immediately.
3. Converting Non‑Terminating Errors Into Terminating Errors¶
You can force a cmdlet to treat non‑terminating errors as terminating errors using:
-ErrorAction Stop
Example¶
Remove-Item "C:\NoSuchFile.txt" -ErrorAction Stop
Now the same missing file produces a terminating error.
This is essential when you want to use try/catch.
4. Using try/catch With Terminating Errors¶
try/catch only works with terminating errors.
Example: catching a terminating error¶
try {
Remove-Item "C:\NoSuchFile.txt" -ErrorAction Stop
}
catch {
"Error caught: $($_.Exception.Message)"
}
Explanation:
ErrorAction Stopforces a terminating error- The
catchblock handles it - The script continues safely
5. Summary of Behavior¶
| Error Type | Script Continues? | Can try/catch Handle It? |
Typical Source |
|---|---|---|---|
| Non‑terminating | Yes | No (unless forced to Stop) | Most cmdlets |
| Terminating | No | Yes | throw, syntax errors, missing commands |
6. When to Use Each Type¶
Use non‑terminating errors when:¶
- Processing large sets of items
- Individual failures should not stop the script
- You want to log errors but continue
Use terminating errors when:¶
- The script cannot continue safely
- A missing value or failure must stop execution
- You want to use
try/catchfor structured error handling