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

Handle a terminating error (exception) within a scriptblock.

Syntax
      try {statement_list}

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

      finally {statement_list}

Key
   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:

Example

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:

Trap - Handle a terminating error
about_Try_Catch_Finally
Looping commands: Do, foreach, ForEach-Object, Switch, While


© Copyright SS64.com 1999-2017
Some rights reserved