LightningWar
LightningWar

Reputation: 975

Error action continue in catch block

My supervisor at work said to always use ErrorAction -Continue in a catch block:

workflow foo {

try {
    Get-CimInstance -ClassName Win32_Product  | ? {$_.Vendor -eq 'Google Inc.'}
    }

catch {
    Write-Error "Something went wrong." -ErrorAction Continue
    Throw
    }
}

What is the benefit of using -EA Continue here? It serves no purpose - throw is executed next and terminates the script anyway.

In both functions and workflows. Is my supervisor correct?

Upvotes: 0

Views: 2573

Answers (1)

Manuel Batsching
Manuel Batsching

Reputation: 3596

I was thinking that -EA Continue was used with Write-Error in this case to make sure that the following Throw gets executed even if the $ErrorActionPreference of the scope was changed to Stop.

Now, that at least is the behaviour in functions.

Workflows seem to be different. I was testing your example with the $ErrorActionPreference set to Stop and 1/0 in the try block to create an exception:

$ErrorActionPreference = 1
workflow foo 
{

    try 
    {
         1/0
    }

    catch 
    {
        Write-Error "Something went wrong." -ErrorAction Continue
        Throw
    }
}

Regardless of the -EA Continue in the line before the Throw doesn't get excecuted in this case. So the $ErrorActionPreference in workflows seems to overwrite any per-cmdlet settings, that are done by the -EA parameter.

As I said, this behaviour is different with functions:

$ErrorActionPreference = 1
function bar 
{

    try 
    {
         1/0
    }

    catch 
    {
        Write-Error "Something went wrong." -ErrorAction Continue
        Throw
    }
}

Here the -ErrorAction Continue makes the difference of the Throw being executed or not.

By the way: if you also want to consider the case that the $ErrorActionPreference was set to SilentlyContinue (and you are not using workflows) than you may want to replace your Throw with Write-Error $_ -EA Continue otherwise your Throw would just silently continue.

So in short: It seems that the -EA parameter is of no effect in your workflow example, if your idea is to be independent of the current $ErrorActionPreference. In functions it makes sense, but in that case the Throw statement should also be avoided.

Upvotes: 1

Related Questions