2009-09-04 31 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