gpt4 book ai didi

.net - PowerShell-为什么不捕获 "Divide By Zero Exception"?

转载 作者:行者123 更新时间:2023-12-04 10:01:24 28 4
gpt4 key购买 nike

在我的计算机上,以下代码片段中的每一个均引发并异常,而不是打印到标准输出“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
}

来自 Windows PowerShell in Action (第257页)

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com