PowerShell with a Purpose Blog

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.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish