BudiBadu Logo
Samplebadu

PowerShell by Example: Error Handling

PowerShell 7

Managing exceptions and errors with this code example demonstrating try-catch-finally blocks for structured error handling, ErrorAction parameter for error behavior control, specific exception type catching, and automatic error variable access.

Code

try {
    # Attempt a risky operation
    $content = Get-Content "nonexistent_file.txt" -ErrorAction Stop
    Write-Host "File read successfully"
}
catch [System.IO.FileNotFoundException] {
    # Handle specific exception
    Write-Warning "File was not found!"
}
catch {
    # Handle all other exceptions
    Write-Error "An unexpected error occurred: $_"
}
finally {
    # Cleanup code (always runs)
    Write-Host "Operation complete"
}

# ErrorAction preference
# SilentlyContinue, Stop, Continue, Inquire

Explanation

PowerShell provides structured exception handling using try, catch, and finally blocks. Code that might throw exceptions is placed in the try block, and if an error occurs, execution jumps to the appropriate catch block. The finally block executes regardless of success or failure, making it ideal for cleanup operations like closing file handles or database connections.

PowerShell distinguishes between terminating and non-terminating errors. Terminating errors stop script execution and can be caught by catch blocks, while non-terminating errors write to the error stream but allow execution to continue. The -ErrorAction parameter controls error behavior with values: Stop converts non-terminating to terminating errors, Continue displays error and continues (default), SilentlyContinue suppresses error display, Inquire prompts user for action, and Ignore completely ignores errors.

Multiple catch blocks can handle different exception types, with specific types checked before generic catches. The automatic variable $_ inside a catch block contains the exception object with properties like Message, Exception, and StackTrace. The $Error automatic variable maintains an array of all errors in the session, with $Error[0] being the most recent error.

Code Breakdown

3
-ErrorAction Stop converts non-terminating error to terminating for catch.
6
[System.IO.FileNotFoundException] catches specific exception type.
10
Generic catch handles all other exception types.
14
finally block executes regardless of success or error.