Exception Handling#

Throwing Exceptions#

  • The command throw "Bad thing happened" creates an exception and interrupts the script execution.
  • The cmdlet Write-Error -Message "Houston, we have a problem." -ErrorAction Stop outputs an error, and setting ErrorAction to Stop causes the script to stop with this error.

Exception Handling#

The principle of error handling in PowerShell is based on the structure:

try {
  # code where an error may occur
}
catch {
  # code to handle the error
}
finally {
  # code that always runs after try/catch
}
  • The code in the try block runs first.
  • If an unresolvable error occurs during the execution of try, control is passed to the catch block. If there are no errors, the catch block is skipped.
  • In the catch block, the automatic variable $PSItem (or $_) of type ErrorRecord is available, which contains details of the exception.
  • The finally block always executes, regardless of whether an error occurred or not. It is used to ensure that important code runs, such as closing connections or releasing resources.
  • You can use both catch and finally at the same time. This allows you to handle errors while always performing cleanup actions, regardless of the outcome.

Example:

try {
  throw "Bad thing happened"
}
catch {
  Write-Host "Error: $($_.Exception.Message)" -ForegroundColor Red
}
finally {
  Write-Host "This block will always execute"
}

In this example, an exception is thrown via throw, then caught in catch, where an error message is displayed, and then the finally block executes, where cleanup code can be placed.

This model simplifies writing robust scripts with error management and resource cleanup.

This approach to exceptions helps create more resilient and maintainable PowerShell scripts, minimizing unexpected interruptions and ensuring timely responses to errors.

Additional information can be found at the link:

everything about exceptionsdocs.microsoft.com