Create and Throw a New Exception in PowerShell

An exception is created when normal error handling can’t deal with the problem. When an exception occurs, we can call it an exception is thrown.
You will need to catch a thrown exception to handle it. If a thrown exception is not caught, the script will stop executing.
This tutorial will teach you how to create and throw an exception in PowerShell.
Use the throw
Keyword to Create and Throw a New Exception in PowerShell
You can create and throw a new exception using the throw
keyword. When an exception is thrown, this will be caught; otherwise, the execution will be stopped.
The following command creates a runtime exception which is a terminating error.
throw "Error occurred."
Output:
Error occurred.
At line:1 char:1
+ throw "Error occurred."
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Error occurred.:String) [], RuntimeException
+ FullyQualifiedErrorId : Error occurred.
It is handled by a catch
in a calling function or exits the script like the above example.
Example code:
function New
{
throw "Error occurred."
}
New
Output:
Error occurred.
At line:3 char:1
+ throw "Error occurred."
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (Error occurred.:String) [], RuntimeException
+ FullyQualifiedErrorId : Error occurred.
Now, let’s see another example using the if
statement.
Example code:
$a=4
$b=5
if ($a -ne $b){
throw "$a is not equal to $b."
}
Output:
4 is not equal to 5.
At line:4 char:1
+ throw "$a is not equal to $b."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (4 is not equal to 5.:String) [], RuntimeException
+ FullyQualifiedErrorId : 4 is not equal to 5.
We hope this tutorial gave you an idea of creating and throwing an exception in PowerShell. For more information, read this post.