Try, Catch and Finally¶
try/catch/finally is PowerShell’s structured mechanism for handling terminating errors. It lets you run code that might fail, react to failures in a controlled way, and perform cleanup actions that must run regardless of success or failure.
1. Basic Syntax¶
try {
<code that may fail>
}
catch {
<code that runs if a terminating error occurs>
}
finally {
<code that always runs>
}
trycontains code that might produce a terminating error.catchruns only if a terminating error occurs.finallyalways runs, whether thetryblock succeeded or failed.
2. Using try/catch¶
catch only triggers on terminating errors.
If a cmdlet normally produces non‑terminating errors, you must force it to stop using -ErrorAction Stop.
Example: catching a terminating error¶
try {
Remove-Item "C:\NoSuchFile.txt" -ErrorAction Stop
}
catch {
"Error caught: $($_.Exception.Message)"
}
Explanation:
Remove-Itemnormally produces a non‑terminating error.ErrorAction Stopconverts it into a terminating error.- The
catchblock handles it. - The script continues safely afterward.
3. Catching Specific Exception Types¶
You can target specific .NET exception types for more precise handling.
try {
[int]"hello" # invalid conversion
}
catch [System.FormatException] {
"Invalid number format."
}
catch {
"General error."
}
Explanation:
- The first
catchhandles format errors. - The second
catchhandles anything else.
This is useful when different errors require different responses.
4. Using finally¶
The finally block runs no matter what happens—whether the try block succeeds, fails, or even if the catch block runs.
Use it for cleanup tasks such as:
- Closing files
- Releasing resources
- Disconnecting sessions
- Resetting state
Example¶
try {
"Opening connection..."
throw "Connection failed."
}
catch {
"Handling error."
}
finally {
"Closing connection."
}
Output:
Opening connection...
Handling error.
Closing connection.
finally always executes.
5. Multiple catch Blocks¶
You can define multiple catch blocks, each handling a different exception type.
PowerShell checks them top‑to‑bottom and uses the first matching one.
try {
Get-Content "C:\missing.txt" -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
"File not found."
}
catch {
"Some other error occurred."
}
6. Re‑throwing Errors¶
If you want to handle an error but still let it propagate upward, use:
throw
Example:
try {
Remove-Item "C:\missing.txt" -ErrorAction Stop
}
catch {
"Logging the error..."
throw # re‑throws the original error
}
7. Summary: How try/catch/finally Works¶
| Block | When It Runs | Purpose |
|---|---|---|
| try | Always | Code that may fail |
| catch | Only on terminating errors | Error handling |
| finally | Always | Cleanup |