- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的计算机上,以下代码片段中的每一个均引发并异常,而不是打印到标准输出“1”和“2”
为什么没有捕获异常(exception)?
try {
[int]$a = 1/0
}
catch {
write 1
}
finally {
write 2
}
try {
[int]$a = 1/0
}
catch [System.Exception] {
write 1
}
finally {
write 2
}
最佳答案
当您使用常量时,解释器将尝试预计算结果并失败,并除以零错误。您的代码甚至都没有执行,因此没有任何陷阱。
您可以通过更改代码以使用变量并强制执行来亲自验证这一点。
try {
$divisor = 0
[int]$a = 1/$divisor
}
catch {
write 1
}
finally {
write 2
}
The example here uses 1/$null. The reason for doing this instead of simply 1/0 is because the PowerShell interpreter does something called constant expression folding.
It looks at expressions that contain only constant values. When it sees one, it evaluates that expression once at compile time so it doesn’t have to waste time doing it again at runtime.
This means that impossible expressions, such as division by zero, are caught and treated as parsing errors. Parsing errors can’t be caught and don’t get logged when they’re entered interactively, so they don’t make for a good example. (If one script calls another script and that script has one of these errors, the calling script can catch it, but the script being parsed cannot.)
关于.net - PowerShell-为什么不捕获 "Divide By Zero Exception"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10618676/
我是一名优秀的程序员,十分优秀!