When is an Error not an Error?

Working with PowerShell can be a bit tricky, and can often require you to have a bit of understanding about how it works. For example, consider these two scenarios:

# one
try { 1 / 0 } catch { write-host 'oops' }

# two
$zero = 0
try { 1 / $zero } catch { write-host 'oops' }

With the first scenario, you'll never actually get your "oops" output. That's because PowerShell never actually executes the illegal divide by zero operation. Instead, it's caught by the parser as it's translating your command into behind-the-scenes executable code. It sees the illegal operation coming and barfs without actually trying it. In the second instance, however, the parser can't see the fail coming because we've put zero into a variable. The parser doesn't look inside variables; because it doesn't see the illegal literal string "/0," it lets the operation proceed to execution - meaning you get an error you can actually catch.

This kinda thing can be really confusing, and it's one of those "gotchas" you just have to pick up from experience. But now you know.

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×