Try/Catch and ErrorAction

This topic contains 3 replies, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 2 months ago.

  • Author
    Posts
  • #13113
    Profile photo of sid351
    sid351
    Participant

    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"?

  • #13114
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

  • #13115
    Profile photo of sid351
    sid351
    Participant

    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?

  • #13116
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    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.

You must be logged in to reply to this topic.