Throw

Generate a terminating error.

Syntax
      throw [expression]
The throw keyword can throw any object, such as a user message string or the object that caused the error.

The expression in the throw syntax is optional. When the throw statement doesn't appear in a catch block, and it doesn't include an expression, it generates a ScriptHalted error.

Don't use the throw keyword for parameter validation, see about_Functions_Advanced_Parameters

Examples

Count to 10:

Throw "User account not found"

Output
Exception: User account not found.

The expression can also be an object that throws the object that represents the PowerShell process:

throw (Get-Process pwsh)

Output
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)

“Nothing is more uncertain than the result of any one throw; few things more certain than the result of many throws. When applied to human life, the law of averages exhibits many striking results” ~ James A. Garfield

Related PowerShell Cmdlets

Break statement
Continue statement
Switch - Check multiple conditions.
Trap - Handle a terminating error.
Try ... Catch - Handle a terminating error within a scriptblock.
Get-ErrorValue - Function to return the Error Codes for Try-Catch-Finally.
Looping commands: Do, For, ForEach-Object, Switch, While


 
Copyright © 1999-2026 SS64.com
Some rights reserved