What’s the difference between the “throw” keyword and “Write-Error -ErrorAction Stop”?

Question:

I’m having trouble googling up a clear answer on this. Are there any practical differences between, for example, throw 'temper tantrum' and Write-Error 'temper tantrum' -ErrorAction Stop?

They both generate terminating errors and set $? to False. I can see that there are differences in the CategoryInfo and FullyQualifiedErrorId. The operative word is practical. Do they have any different effects? Are there reasons to prefer one over the other in particular situations?

Answer:

throw generates a terminating error, Write-Error without -ErrorAction Stop would generate a non-terminating error. Since -ErrorAction Stop turns the non-terminating into a terminating error, the two instructions are basically the same.

There are differences, though. throw <expression> populates $error[0].TargetObject with <expression>, while Write-Error <expression> -ErrorAction Stop does not.

Source:

What’s the difference between the “throw” keyword and “Write-Error -ErrorAction Stop”? by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply