2009-09-04 28 views
3

我不明白为什么我看到这种行为在PowerShell中: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 

为什么一个表达触发陷阱和其他不?

回答

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. 

然后陷阱火灾因为解析器再也不能预先计算值。

+0

有道理。为了进一步支持你,这个: trap {“Got it!” } invoke-expression“1/0” 给出了预期的行为。 – zdan 2009-09-04 17:54:07