Powershell陷阱不会被持续触发

时间:2009-09-04 16:48:07

标签: powershell error-handling powershell-trap

我无法理解为什么我在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

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

1 个答案:

答案 0 :(得分: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.

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

相关问题