Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
853 views
in Technique[技术] by (71.8m points)

.net - PowerShell - Why "Divide By Zero Exception" is not being Caught?

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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...