throw keyword that generates a terminating error.
throw keyword causes a terminating error. You can use the
to stop the processing of a command, function, or script.
For example, you can use the
throw keyword in the script block of an
statement to respond to a condition or in the
catch block of a
throw keyword can throw any object, such as a user message string or the
object that caused the error.
The syntax of the
throw keyword is as follows:
The expression in the
throw syntax is optional. When the
doesn't appear in a
catch block, and it doesn't include an expression, it
generates a ScriptHalted error.
throw keyword is used in a
catch block without an expression, it
throws the current RuntimeException again. For more information, see
Throwing a string
The optional expression in a
throw statement can be a string, as shown in the
throw "This is an error."
Exception: This is an error.
Throwing other objects
The expression can also be an object that throws the object that represents the PowerShell process, as shown in the following example:
throw (Get-Process pwsh)
Exception: System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh) System.Diagnostics.Process (pwsh)
You can use the TargetObject property of the ErrorRecord object in the
$Error automatic variable to examine the error.
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 125 174.44 229.57 23.61 1548 2 pwsh 63 44.07 81.95 1.75 1732 2 pwsh 63 43.32 77.65 1.48 9092 2 pwsh
You can also
throw an ErrorRecord object or a .NET exception. The
following example uses the
throw keyword to throw a
$formatError = New-Object System.FormatException throw $formatError
OperationStopped: One of the identified items was in an invalid format.
The resulting error
throw keyword can generate an ErrorRecord object. The Exception
property of the ErrorRecord object contains a RuntimeException object.
The remainder of the ErrorRecord object and the RuntimeException object
varies depending on the object thrown.
throw object is wrapped in an ErrorRecord object, and the ErrorRecord
object is automatically saved in the
$Error automatic variable.
throw to create a mandatory parameter
Unlike past versions of PowerShell, don't use the
throw keyword for parameter
for the correct way.
Submit and view feedback for