3

我不明白为什么我在 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

为什么一个表达式会触发陷阱而另一个不会?

4

1 回答 1

5

我认为您的第一个案例是解析错误。那就是解析器正在尝试进行常量折叠(预先计算值)和错误,因为它得到了除以零的异常。其他语法错误的行为方式相同,即它们不会触发陷阱:

trap { "Got it!" } 1/;
You must provide a value expression on the right-hand side of the '/' operator.

如果您将代码更改为:

$denom = 0
trap { "Got it!" } 1/$denom
Got it!
Attempted to divide by zero.

然后陷阱触发,因为解析器不能再预先计算该值。

于 2009-09-04T17:42:46.570 回答