🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Error Handling

Error handling means catching a failure and answering it calmly instead of stopping. A try block holds risky commands, and a catch block runs only when one of them fails.

Catch a missing path

Get-Item looks for a path that does not exist. With -ErrorAction Stop, the catch block prints its message.

try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message }

Catch a divide by zero

Dividing by zero always fails. The catch block prints the plain message for that failure.

try { 1/0 } catch { "Caught: " + $_.Exception.Message }

A try block that succeeds

When nothing in try fails, the catch block never runs. The file content prints as normal.

Set-Content -Path "hello.txt" -Value "hello"
try { Get-Content -Path "hello.txt" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message }

Example

Set-Content -Path "good.txt" -Value "ready"
try { Get-Content -Path "good.txt" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message }
try { Get-Content -Path "/definitely-not-here-xyz.txt" -ErrorAction Stop } catch { "Caught: " + $_.Exception.Message }

Key points

  • try: a block that holds commands that might fail.
  • catch: a block that runs only when a command in try fails.
  • ErrorAction Stop: a parameter that turns a failure into a catchable error.
  • Exception Message: the plain-words message that explains what went wrong.

In this example, the first try reads a file that exists, so its content prints and its catch never runs. The second try reads a path that does not exist, so its catch prints the plain message for the missing path.

Note

print only the exception message, never raw error text, because raw error text includes machine-specific paths.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What runs when a command inside try succeeds?