Try {...} Catch {...} Finally {...}

Handle a terminating error (exception) within a scriptblock.

      try {statement_list}

      catch [[error_type][',' error_type]*] {statement_list}

      finally {statement_list}

   statement_list   A scriptblock of code to be run

The Try block defines a section of a script to be monitored for errors. If an error occurs within the Try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a Catch block to handle the error.

If the Try statement does not have a matching Catch block, PowerShell continues to search for an appropriate Catch block or Trap statement in the parent scopes.

After a Catch block is completed or if no appropriate Catch block or Trap statement is found, the Finally block is run.

If the error cannot be handled, the error is written to the error stream.

To free resources used by a script, add a Finally block after the Try and Catch blocks. PowerShell runs the Finally block before the script terminates or before the current block goes out of scope.

The Finally block statements will run:


Attempt running a non existent cmdlet:

try { NoSuchCmdlet }
catch { "That cmdlet does not exist." }

When run, the above script will return: That cmdlet does not exist.

"Do or do not. There is no try” ~ Yoda

Related PowerShell Cmdlets

Trap - Handle a terminating error.
Get-ErrorValue - Function to return the Error Codes for Try-Catch-Finally.
Looping commands: Do, foreach, ForEach-Object, Switch, While

Copyright © 1999-2024
Some rights reserved