Search notes:

PowerShell: try … catch … finally statements

In a trycatch statement sequence, PowerShell tries to execute the statements of the try block. If an exception is thrown (throw statement), the execution of the statements in the try block is left (for good) and the statements in the catch block are executed.
In a catch block, the exception object that describes the error condition can be queried through the automatic variable $_ ($psItem).
An optional finally block may follow the catch block. It contains the statements that need to be executed regardless of an exception was thrown in the try block. Usually, the finally block is used for cleaning up resources that might have been allocated in the catch block.
function divide-by($num) {

  try {

    write-output "42 / $num = $(42/$num)"

  }
  catch {

    write-output "Exception $_"

  }
  finally {

    write-output "The finally block is always executed";

  }

}

divide-by 7
divide-by 6
divide-by 0
divide-by 3
Github repository about-Powershell, path: /language/statement/try-catch-finally/simple.ps1

Catch a specific type

If a class (such as ExOne in the following example) is derived from System.Exception), an object of that type can be specifically caught in the catch handler (catch [ExOne]).
Because ExTwo does not derive from System.Exception, it is not possible to specifically catch this type.
class ExOne : System.Exception {}
class ExTwo                    {}

function throwException($num) {

   if ($num -eq 1) {
      throw [ExOne]::new()

   }
   if ($num -eq 2) {
      throw [ExTwo]::new()
   }
}

function tryToCatch($num) {
   try {
      throwException $num
      write-host 'no exception'
   }
   catch [ExOne] {
      write-host "Caught: ExOne"
   }
   catch [ExTwo] {
      write-host "Caught: ExTwo"
   }
   catch {
      write-host "Caught neither ExOne nor ExTwo: `$_ = $_"
   }

}

tryToCatch 1
#
#  Caught: ExOne

tryToCatch 2
#
#  Caught neither ExOne nor ExTwo: $_ = ExTwo

tryToCatch 3
#
#  no exception
Github repository about-Powershell, path: /language/statement/try-catch-finally/catch-type.ps1

See also

In a catch block, the automatic variable $_ is an instance of of an System.Management.Automation.ErrorRecord object that describes the error in more detail.
The trap statement
Error handling in PowerShell
Other statements

Index