Error Handling Discussion

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

  • Author
    Posts
  • #13153
    Profile photo of Rob Campbell
    Rob Campbell
    Participant

    Ed offers this example of using $ErrorActionPreference:

    Try {

    $ErrorActionPreference = "Stop"

    Copy-Item -Path $myfile -Destination $folder -Force }

    CATCH [System.Exception]{

    MD $folder | Out-Null

    Copy-Item -Path $myfile -Destination $folder -Force }

    FINALLY { $ErrorActionPreference = "Continue" }

    You can also do this:

    &{
    Try {

    $ErrorActionPreference = "Stop"

    Copy-Item -Path $myfile -Destination $folder -Force }

    CATCH [System.Exception]{

    MD $folder | Out-Null

    Copy-Item -Path $myfile -Destination $folder -Force }
    }

    Which isolates the $ErrorActionPreference in it's own scope. You don't have to worry about adding a FINALLY block to set it back. Since $ErrorActionPreference never changed in the parent scope, you also don't have to worry about whether setting it to 'Continue' will change what it was originally set to.

  • #13160
    Profile photo of Don Jones
    Don Jones
    Keymaster

    All true. You have to be a bit careful with that technique, because any variables you create in that scope obviously won't persist in the rest of the script, but it's definitely an approach.

    With cmdlets, of course, you can also use -ErrorAction on the cmdlet, which confines it to just that one command without creating a new scope.

    And I suppose I could also argue that, with this specific example, Test-Path could have been used to avoid the error entirely. I personally tend to prefer test-and-recover vs. error-and-catch, when I'm in a situation to do so.

  • #13161
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    I almost never wind up having to touch $ErrorActionPreference in a script, other than for demonstration purposes. I just use the ErrorAction parameter, and leave the preference variable alone.

  • #13179
    Profile photo of Rob Campbell
    Rob Campbell
    Participant

    The example is trivial enough that applying -ErrorAction to the relevant cmdlets instead of setting $ErrorActionPreference is pretty obvious. I'd consider setting it in a situation where I had a more complex script block where every operation depended on successful completion of all the ones before it, and any error should cause an immediate exit to the Catch block. Using the script block invocation to run it in it's own scope and protect the preference variable in the parent scope is just utilizing a scope for a purpose it was designed for. (IMHO).

You must be logged in to reply to this topic.