PowerShell的 - 为什么"被零除例外"是不是被抓?被抓、PowerShell、QUOT

由网友(素衣白裙清浅微笑°)分享简介:在我的机器下面的code段中的每一个抛出和异常,而不是打印到标准输出1和2为什么异常没有被抓?尝试{[INT] $ A = 1/0}抓住 {写1}最后 {写2}尝试 {[INT] $ A = 1/0}赶上[System.Exception的] {写1}最后 {写2}解决方案 由于您使用的是常量,跨...

在我的机器下面的code段中的每一个抛出和异常,而不是打印到标准输出1和2 为什么异常没有被抓?

 尝试{
    [INT] $ A = 1/0
}
抓住 {
    写1
}
最后 {
    写2
}

尝试 {
    [INT] $ A = 1/0
}
赶上[System.Exception的] {
    写1
}
最后 {
    写2
}
 

解决方案

由于您使用的是常量,跨preTER试图precompute结果和失败,除以零误差。您的code甚至没有得到执行,所以没有什么陷阱。

Getting Started with PowerShell 3.0 09 Introducing scripting and toolmaking

您可以通过更改code使用变量,强制其执行验证自己这一点。

 尝试{
    $除数= 0
    [INT] $ A = 1 / $除数
}
抓住 {
    写1
}
最后 {
    写2
}
 

在的Windows PowerShell在行动(第257页)

  

这个例子中,使用了1 / $空。这样做的原因,而不是本   仅仅1/0是因为PowerShell的跨preTER做一些所谓的   恒恩pression折叠。

     

它着眼于只含有常量EX pressions。当   可以看到一个,它的计算结果是EX pression一次在编译时间,所以   不必浪费时间在运行时的老毛病又犯了。

     

这意味着,不可能EX pressions,如被零除,是   捕获并处理为解析错误。解析错误不能被捕获   而当他们交互的方式输入也登录不上去,所以他们不   使一个很好的例子。 (如果有一个脚本调用另一个脚本和   脚本有一个这些错误,调用脚本可以赶上它,但   脚本被解析不了。)

On my Machine each one of the following code snippets throws and exception instead of printing to the standard output "1" and "2" Why the exception is not being Caught?

try {
    [int]$a = 1/0
}
catch {
    write 1
}
finally {
    write 2
}

try {
    [int]$a = 1/0
}
catch [System.Exception] {
    write 1
}
finally {
    write 2
}

解决方案

As you are using constants, the interpreter tries to precompute the result and fails with a division by zero error. Your code does not even get executed so there's nothing to trap.

You can verify this for yourself by changing your code to use variables, forcing it to be executed.

try {
    $divisor = 0
    [int]$a = 1/$divisor
}
catch {
    write 1
}
finally {
    write 2
}

From Windows PowerShell in Action (p.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.)

阅读全文

相关推荐

最新文章