Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 34 ยท Files, Data and Errors

Errors, try/catch and ErrorAction

Understand PowerShell terminating and non-terminating errors, -ErrorAction, $ErrorActionPreference, try/catch/finally and the $Error list, with runnable models.

Scripts fail: a file is missing, a server does not answer, a user lacks permission. What matters is what your script does next. PowerShell has a more layered error system than most languages, and the first surprise for newcomers is that a try/catch block often does not catch a failing cmdlet. Understanding why is the key to this lesson.

The commands below are real PowerShell and are read-only here. To make the rules visible, the runnable examples are JavaScript models of the error system: they follow the documented behavior, but they are stand-ins, not PowerShell.

Two kinds of errors

PowerShell separates errors by whether they stop the current statement:

Non-terminating errors

Reported, not fatal The cmdlet writes an error and keeps going.
Per item One bad file, the rest still get processed.
Not caught try/catch ignores them by default.

Most cmdlet failures are of this kind.

1 / 2

A non-terminating error is written to the error stream and the cmdlet carries on with the next input. Get-Item a.txt, missing.txt, c.txt prints an error for the missing file and still returns the other two. This design suits administration work, where one broken item should not abort a thousand good ones.

A terminating error stops the running statement. You create one with throw, and the engine raises them for things like calling a method on $null, a failed type conversion or a .NET exception thrown inside a method call. Parse errors in a script are terminating too, and stop it before any line runs.

POWERSHELL
Write-Error 'Disk almost full'      # non-terminating: script continues
throw 'Disk almost full'            # terminating: script stops (unless caught)

Controlling the reaction with -ErrorAction

Every cmdlet has the common parameter -ErrorAction, which decides what happens to its non-terminating errors:

Value Meaning
Continue The default: print the error and keep going
SilentlyContinue Do not print it, keep going; the error is still stored in $Error
Ignore Do not print it and do not store it in $Error
Stop Turn it into a terminating error
Inquire Ask the user what to do

The variable $ErrorActionPreference sets the default for the whole scope. A script that should fail fast often starts with $ErrorActionPreference = 'Stop'.

POWERSHELL
Get-Item .\a.txt, .\missing.txt, .\c.txt                       # error printed, two files returned
Get-Item .\a.txt, .\missing.txt, .\c.txt -ErrorAction Stop     # stops at the missing file
Get-Item .\missing.txt -ErrorAction SilentlyContinue           # quiet, nothing returned

-ErrorAction Stop is the bridge between the two kinds of errors: it upgrades a non-terminating error to a terminating one, which is what lets try/catch see it.

The model below plays out the three behaviors on three file names.

JS Non-terminating errors and -ErrorAction

Press Run (or Ctrl + Enter) to see the console output here.

No output.

With Continue and SilentlyContinue both good files come back. Only Stop ends the work early, and only Ignore leaves no trace in the error list. In real PowerShell $Error also contains richer ErrorRecord objects, not just text.

try, catch and finally

try/catch/finally handles terminating errors:

POWERSHELL
try {
    $text = Get-Content .\settings.json -Raw -ErrorAction Stop
    $settings = $text | ConvertFrom-Json
    Write-Output "Loaded $($settings.name)"
}
catch [System.Management.Automation.ItemNotFoundException] {
    Write-Warning "settings.json is missing, using defaults"
}
catch {
    Write-Error "Unexpected problem: $($_.Exception.Message)"
    throw          # re-throw the same error to the caller
}
finally {
    Write-Output "Done"   # always runs, error or not
}

Several details matter:

  • -ErrorAction Stop is what makes this work. Without it, a missing file is non-terminating and catch never runs.
  • Catch blocks are tried in order, and the first that matches wins. Put specific exception types first and a general catch last.
  • Inside catch, $_ (also $PSItem) is an ErrorRecord. Use $_.Exception.Message for the text, $_.CategoryInfo for the category and $_.InvocationInfo.ScriptLineNumber for the line.
  • A bare throw inside catch rethrows the current error. throw 'text' raises a new one.
  • finally runs after try and any catch, even when an error is rethrown. Use it to close files, release locks and remove temporary data.

The $Error list and $?

$Error is a list of recent errors with the newest at index 0. $Error[0] is the last error, $Error.Clear() empties it. To capture the errors of a single command, use -ErrorVariable:

POWERSHELL
Get-Item .\missing.txt -ErrorAction SilentlyContinue -ErrorVariable problems
$problems.Count              # 1
$problems[0].Exception.Message

After any command, $? is $true if the last operation succeeded and $false if it reported an error. For external programs such as git or robocopy, the exit code is in $LASTEXITCODE, and a non-zero exit code is not a PowerShell error by itself. Check it yourself:

POWERSHELL
git status
if ($LASTEXITCODE -ne 0) { throw "git failed with exit code $LASTEXITCODE" }

Recent PowerShell 7 versions can also treat failing native commands as errors through the $PSNativeCommandUseErrorActionPreference setting; check that your version supports it before relying on it.

The second model shows try/catch/finally ordering, typed catch blocks and rethrow.

JS try, typed catch, finally and rethrow

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that finally printed in every case, even for boom, where the error was rethrown to the caller. The typed catch blocks mirror catch [TypeName] in PowerShell, where the first matching block wins; JavaScript has no typed catch syntax, so the model uses instanceof checks inside one catch.

Practical guidance

  1. Set $ErrorActionPreference = 'Stop' at the top of scripts that must not continue after a failure, or pass -ErrorAction Stop on the calls inside try blocks.
  2. Catch only what you can handle. A silent catch { } hides real bugs.
  3. Use Write-Error for problems callers may want to handle, throw for failures that must end the work.
  4. Prefer Test-Path and similar checks when a missing item is an expected case rather than an error.
  5. Always check $LASTEXITCODE after native programs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A try block contains Get-Content .\missing.txt with no extra parameters. Why does the catch block not run?

    Most cmdlet errors are non-terminating. Add -ErrorAction Stop (or set $ErrorActionPreference to 'Stop') to turn them into terminating errors that catch can handle.
  2. 2. What is the difference between -ErrorAction SilentlyContinue and Ignore?

    Both hide the message and continue. SilentlyContinue still records the error in $Error; Ignore does not.
  3. 3. Where is the most recent error in the $Error list?

    $Error is ordered newest first, so $Error[0] is the latest error.
  4. 4. git exits with code 1 inside your script. What does PowerShell do by default?

    A non-zero exit code from an external program is not treated as a PowerShell error. Test $LASTEXITCODE yourself.
  5. 5. When does the finally block run?

    finally is for cleanup and always runs, even when an error is rethrown.

Summary

  • Non-terminating errors are reported while the cmdlet continues; terminating errors stop the statement and are what try/catch handles.
  • -ErrorAction Stop (or $ErrorActionPreference = 'Stop') upgrades non-terminating errors; SilentlyContinue hides them but keeps them in $Error, Ignore hides and discards.
  • In catch, $_ is an ErrorRecord; use $_.Exception.Message, order specific catches before general ones, and rethrow with a bare throw.
  • finally always runs and is the place for cleanup.
  • $Error[0] is the newest error, -ErrorVariable captures a command's errors, and $LASTEXITCODE reports external programs.

Next, process text with Regular Expressions and Text Processing.