This topic contains 3 replies, has 2 voices, and was last updated by
February 14, 2014 at 4:22 pm #13113ParticipantPoints: 0Rank: Member
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"?
February 14, 2014 at 5:20 pm #13114MemberPoints: 0Rank: Member
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.
February 14, 2014 at 5:51 pm #13115ParticipantPoints: 0Rank: Member
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?
February 14, 2014 at 6:43 pm #13116MemberPoints: 0Rank: Member
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.
The topic ‘Try/Catch and ErrorAction’ is closed to new replies.