PowerShell的陷阱不被触发一致
-
21-09-2019 - |
题
我不明白为什么我看到在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
为什么一个表达触发陷阱和其它不?
解决方案
我会考虑你的第一个案件是一个解析错误。这是解析器正试图在这一点上做的常量折叠(预先计算的值)和错误,因为它零异常得到一个鸿沟。行为相同的方式的其他语法错误即它们不触发陷阱:
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.
然后陷阱火灾因为解析器不再能预先计算的值。
不隶属于 StackOverflow