views:

328

answers:

1

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?

+5  A: 

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.

Keith Hill
Makes sense. To further back you up, this:trap { "Got it!" } invoke-expression "1/0"gives the expected behaviour.
zdan