How to Use Try Catch in PowerShell for Error Handling
In PowerShell, use
try to run code that might cause errors and catch to handle those errors gracefully. Place the risky code inside try { } and error handling code inside catch { } blocks to control what happens when an error occurs.Syntax
The try block contains code that might throw an error. The catch block runs only if an error happens inside try. Optionally, finally runs code after try and catch, no matter what.
- try { }: Code that may cause an error.
- catch { }: Code to handle the error.
- finally { } (optional): Code that always runs last.
powershell
try { # Code that might fail } catch { # Code to handle error } finally { # Code that runs always (optional) }
Example
This example tries to divide a number by zero, which causes an error. The catch block catches the error and prints a friendly message.
powershell
try { $result = 10 / 0 Write-Output "Result is $result" } catch { Write-Output "Oops! You cannot divide by zero." }
Output
Oops! You cannot divide by zero.
Common Pitfalls
One common mistake is not enabling error handling properly. PowerShell treats some errors as non-terminating by default, so try catch won't catch them unless you set $ErrorActionPreference = 'Stop' or use -ErrorAction Stop.
Also, avoid putting code that cannot fail inside try to keep your script clean.
powershell
try { Get-Item 'C:\nonexistentfile.txt' } catch { Write-Output "File not found error caught." } # This won't catch error because Get-Item error is non-terminating by default # Correct way: try { Get-Item 'C:\nonexistentfile.txt' -ErrorAction Stop } catch { Write-Output "File not found error caught with -ErrorAction Stop." }
Output
File not found error caught with -ErrorAction Stop.
Quick Reference
Remember these tips when using try catch in PowerShell:
- Use
-ErrorAction Stopor set$ErrorActionPreference = 'Stop'to catch errors. catchruns only on terminating errors.finallyruns always, useful for cleanup.- Keep
tryblocks focused on risky code only.
Key Takeaways
Use try { } to run code that might fail and catch { } to handle errors.
Set -ErrorAction Stop or $ErrorActionPreference = 'Stop' to catch non-terminating errors.
finally { } runs code regardless of errors, useful for cleanup.
Keep try blocks small and focused on code that can cause errors.
Catch blocks help keep scripts running smoothly by managing errors gracefully.