Try/Catch and ErrorAction

Hi there,

Following some comments on our scorecard in the Scripting Games I’m not sure I understand how Try/Catch is applied in PowerShell.

I thought any error a cmdlet generates would be caught and pushed into the respective Catch (depending on exception types).

Is this not the case? Do some cmdlets do this by default and others not? If so, how do I tell if I need to add “-ErrorAction Stop”?

Try/Catch will only intercept Terminating errors. Most errors from cmdlets are Non-Terminating, so if you want to handle them with Try/Catch, you need to set ErrorAction (or $ErrorActionPreference) to Stop to force them to become terminating instead.

Converting non-terminating errors into terminating errors may not always be desirable, though; this causes your entire pipeline to abort on the first error, instead of continuing to process other input objects. In those situations, try/catch won’t help you (except to handle a terminating error if one occurs), so you need to use $error or -ErrorVariable instead.

In general, I just stick -ErrorAction Stop onto any command that I’m placing into a Try/Catch block, just in case. Even if you know you don’t need it, it doesn’t hurt anything, and makes the intent clear to anyone who’s reading the code.

Thanks for that.

Considering your point about killing the pipe and forcing the Stop value, do you have any suggestions on when to use Try/Catch?

Mainly when you’re running a command against a single input object, instead of passing in multiples (via the pipeline or an array). In that case, there’s no point in having any distinction between a terminating and non/terminating error anyway, so you may as well force them all to be terminating so you can use try/catch.