PowerShell - Why "Divide By Zero Exception" Misses?

On my computer, each of the following code fragments generates and excludes instead of printing to the standard output “1” and “2”, Why does the exception not get there?

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

try {
    [int]$a = 1/0
}
catch [System.Exception] {
    write 1
}
finally {
    write 2
}
+5
source share
3 answers

Since you use constants ,, the interpreter tries to precompile the result with a division by zero error. Your code doesn't even execute, so you have nothing to catch.

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

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

From Windows PowerShell in action (p. 257)

1/$null. 1/0 - , PowerShell -, .

, . , , .

, , , . , theyre , . ( script script script , script , script .)

+10

RuntimeException v2 . 3.

.

+4

You can try to throw an exception using this line: trap { "Your Exception" } 1/0
This will throw a division by 0 exception. Although I really don't understand why your code does not throw an exception ._.
PS: Shouldn't that be catch [System.SystemException]? :)

+1
source

All Articles