Try … Catch - PowerShell


Overview

The Try ... Catch block in PowerShell is a structured exception-handling mechanism that allows you to handle errors gracefully and resume execution without crashing the script.

Syntax

Try {
    # Code to execute
}
Catch [Parameter-List] {
    # Code to execute when an error occurs
}

Parameters

  • Try: The block of code to be executed.
  • Catch: The block of code to be executed when an error occurs within the Try block.
  • Parameter-List: Specifies the type of error to catch. Can include multiple types separated by commas.

Options/Flags

None

Examples

Simple Exception Handling

Try {
    $filePath = 'non-existing-file.txt'
    Get-Content $filePath
}
Catch {
    Write-Warning "File not found: $filePath"
    # Resume script execution
}

Catching Specific Exceptions

Try {
    $num = 10 / 0
}
Catch [System.DivideByZeroException] {
    Write-Warning "Division by zero error"
}
Catch [System.ArgumentNullException] {
    Write-Warning "Argument null error"
}

Multiple Try ... Catch Blocks

Try {
    Get-Content $filePath1
}
Catch [FileNotFoundException] {
    Write-Warning "File not found: $filePath1"
}
Try {
    Get-Content $filePath2
}
Catch {
    Write-Warning "File not found: $filePath2"
}

Common Issues

  • Unhandled Exceptions: If an error is not handled within a Catch block, the script will terminate abruptly.
  • Catching Too Broad: Catching too many error types can mask actual problems and make debugging difficult.
  • Executing After Error: Ensure that the Resume keyword is used within the Catch block to prevent re-execution of the Try block.

Integration

Try ... Catch can be used in conjunction with other error-handling mechanisms such as:

  • Throw: Raises an error manually.
  • Finally: Always executes, regardless of errors.