Catch - PowerShell
Overview
The Catch
command in PowerShell allows you to handle exceptions and errors that occur within a script. It’s essential for capturing and managing exceptions in an organized and controlled manner.
Syntax
Catch [-ExceptionType] <String> [-WarningAction] <WarningAction>
Catch -All
Catch -Default
Options/Flags
- -ExceptionType
: Specifies the specific exception type to catch. - -WarningAction
: Controls how warnings are handled. Default: Continue. - -All: Catches all exceptions including non-terminating errors.
- -Default: Catches all terminating errors.
Examples
Example 1: Catching a specific exception type:
try {
$result = Get-Item "non-existent.txt"
} catch [System.IO.FileNotFoundException] {
Write-Host "File not found. Continuing..."
}
Example 2: Catching all exceptions:
try {
$result = Get-Item "non-existent.txt"
} catch -All {
Write-Host "An error occurred. Continuing..."
}
Example 3: Suppressing warnings:
try {
Get-ChildItem -Path "non-existent.txt" -ErrorAction SilentlyContinue
} catch -Default {
Write-Error "An error occurred."
}
Common Issues
- Exception not caught: Ensure the -ExceptionType parameter aligns with the expected exception type.
- Excessive warning suppression: Use
-WarningAction
cautiously to avoid suppressing critical warnings.
Integration
Using Catch
with Throw
:
Throw -Error "MyError"
Catch -Default {
Write-Error "Error handling code for custom error."
}
Combining Catch
with other commands:
Get-ChildItem -ErrorAction Stop | Catch -Default {
Write-Error "Error handling code for stopped command."
}
Related Commands
Try
Throw
ErrorAction