Powershell trap not being triggered consistently
-
21-09-2019 - |
Question
I can't understand why I'm seeing this behavior in Powershell:
PS C:\> trap { "Got it!" } 1/0
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/0 <<<<
PS C:\> trap { "Got it!" } 1/$null
Got it!
Attempted to divide by zero.
At line:1 char:22
+ trap { "Got it!" } 1/$ <<<< null
Why does one expression trigger the trap and the other doesn't?
Solution
I would consider your first case to be a parse error. That is the parser is attempting to do constant folding (precomputing the value) and errors at that point because it gets a divide by zero exception. Other syntax errors behave the same way i.e. they don't trigger the trap:
trap { "Got it!" } 1/;
You must provide a value expression on the right-hand side of the '/' operator.
If you change the code to this:
$denom = 0
trap { "Got it!" } 1/$denom
Got it!
Attempted to divide by zero.
Then the trap fires because the parser can no longer precompute the value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow