Understanding Exceptions (and why you can’t catch some errors)

by Dec 12, 2008

Traps are a great way of catching exceptions and handling errors manually but this does not seem to work all of the time. This example catches the error:

Trap { 'Something terrible happened.'; Continue}
1/$null

However, this example does not:

Trap { 'Something terrible happened.'; Continue}
1/0

And this one doesn’t seem to work either:

Trap { 'Something terrible happened.'; Continue}
Dir c:\nonexistentfolder

The reason: the last two examples did not raise an exception, and thus your Trap never noticed the error. Some very obvious errors such as 1/0 are discovered by the PowerShell parser and raises an error without even bothering to start the script (and your Trap). You cannot trap those and should fix these syntactical errors right away.

Other errors are handled by the commands internally. When you try and list a folder content of a folder that does not exist, the Get-ChildItem cmdlet (alias Dir) will raise the error and handle it internally.

So, for your traps to work, you will need to set the $ErrorActionPreference to ‘Stop’. Only then will errors raise external exceptions that your traps can handle. You can set the error preference either individually with the -EA parameter:

Trap { 'Something terrible happened.'; Continue}
Dir c:\nonexistentfolder -EA Stop

Or, you change $ErrorActionPreference inside your script so the new error preference is valid for all commands in your script:

$ErrorActionPreference = 'Stop'
Trap { 'Something terrible happened.'; Continue}
Dir c:\nonexistentfolder

If you run your script isolated, you will not need to reset $ErrorActionPreference. If you run your script dot-sourced in global scope, you might want to reset $ErrorActionPreference to the default ‘Continue’ at the end of your script.