🎓 A1Learner
🔍
0 of 47 lessons completed

PowerShell Try Catch Finally

A try-catch-finally block tries code, catches an error if one happens, and always runs a cleanup block at the end. The cleanup block runs on the success path and on the error path alike.

Finally runs on the success path

Nothing fails in the try block, and finally still runs. The result prints after the finally line.

try { $result = 2 + 3 } catch { "Caught" } finally { "Finally ran" }
$result

Finally runs on the error path

The missing path fails, the catch prints the message, and finally still runs after the catch.

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

Finally cleans up a temp file

The script creates a temp file, does its work, and removes the file in finally. The final check prints False, which proves the cleanup happened.

$file = Join-Path $PSScriptRoot "cleanup-demo.txt"
Set-Content -Path $file -Value "temp"
try { "work done" } finally { Remove-Item -Path $file }
Test-Path $file

Example

$file = Join-Path $PSScriptRoot "cleanup-demo.txt"
Set-Content -Path $file -Value "temp"
try {
  try { Get-Item "/definitely-not-here-xyz" -ErrorAction Stop } catch { "Inner caught: " + $_.Exception.Message }
  "Outer continued"
} catch { "Outer caught" } finally { Remove-Item -Path $file; "Cleaned up" }
Test-Path $file

Key points

  • Finally block: a block that runs after try and catch, on both the success path and the error path.
  • Cleanup job: finally is the place for cleanup work, such as removing a temp file the script created.
  • Catch first: when an error happens, the catch block runs first and the finally block runs after it.
  • No error needed: finally runs even when no error happens at all.
  • Nested try: a try block inside another try block lets the inner catch handle an error while the outer block keeps going.

In this example, the script creates a temp file and runs a nested try block. The inner catch handles the missing path error, the outer block continues, and the outer finally removes the temp file, which the final check proves.

Note

finally cannot stop an error from reaching catch, it only adds work that always runs.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A script creates a temp file, then fails inside try. Where should the removal of the temp file go so it always happens?