I am running the following power shell script using power shell console:
$ob1 = "nonexistingclass"
$a = new-object $ob1
Write-Output "Created new object"
Write-Output "End"
This prints the error. And then continues and prints the "Created new object" and "End". So I am assuming this is a non terminating error.
But if I put try catch block around the new-object as follows:
$ob1 = "nonexistingclass"
try
{
$a = new-object $ob1
Write-Output "Created new object"
}
catch
{
Write-Error "Exception Message: $($_.Exception.Message)"
}
Write-Output "End"
In this case catch block is hit and it writes the exception message.
My questions are:
Terminating errors don't always mean that the script will stop executing, it usually just means that they throw a PipelineStoppedException
, meaning that processing will stop on that pipeline, but will continue executing the rest of the script. So to answer your questions, yes, it is a terminating error, but it is not stopping the execution of the entire script, this is why it hits the catch block.
The -ErrorAction stop switch just effectively makes the cmdlet throw a terminating error so that you can catch the error, it will not stop the script (hence why your last line is still executed). If you want the script to stop you would put the Exit
command in the catch block to end the script at that point.
See:
Terminating Errors
Non-Terminating Errors
According to the documentation, there are two types of PowerShell errors, terminating and non-terminating.
There is yet another obscure third type of errors. Such errors are caught by
try
and trap
, i.e. they behave like terminating, but they do not stop
execution without try
or trap
, i.e. they behave like non-terminating.
For example, if a command name is not recognized as the name of a cmdlet, function, script file, or operable program then PowerShell emits an error. Is this error terminating or not? It depends. By default it is not, surprisingly.
It looks like constant use of either error action preference Stop or try
or
trap
blocks in scripts is a good idea. Otherwise semi-terminating errors may
cause problems because invocation continues. Note that the default error action
preference is Continue.
Examples of semi-terminating errors:
The list may continue...
Hypothesis
The tests give the idea that any runtime exception is a semi-terminating error.
See the full case with test scripts - PowerShellTraps/Errors-of-unusual-type
UPDATE (as discussed in comments):
There is not much official documentation about such error details. But here is the comprehensive discussion at the PowerShell documentation repository:
https://github.com/MicrosoftDocs/PowerShell-Docs/issues/1583
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With