In the example below I want to catch the Error with -ErrorAction Stop. It worked perfectly in this case.
try
{ Import-Module -ErrorAction Stop -Force nomodule.psm1
}
catch
{ Write-Host -ForegroundColor Red "no module" $PSItem >> $env:HOMEPATH\AVSUB.log exit 1
}But in the case below, I did not use -ErrorAction Stop and the catch block still ran.
try
{ $var= broken_function
}
catch
{ Write-Host -ForegroundColor Red "error" $PSItem >> $env:HOMEPATH\AVSUB.log exit 1
}Why do I sometimes need to specify -ErrorAction Stop and sometimes not?
1 Answer
There are Terminating and Non-Terminating Errors in PowerShell.
A terminating error is an error that halts the execution of a cmdlet, script or program. This will be caught by Try {} Catch {} without the need of -ErrorAction Stop.
Non-terminating errors allow PowerShell to continue the execution. You can catch them, by adding -ErrorAction Stop.
Here are two functions, one produces a terminating error, the other a non-terminating error.
# This will throw a terminating error
function TerminatingErrorExample { [CmdletBinding()] Param() Throw "I can't run like this!" Write-Host "This message will never be displayed, because it's after the terminating error."
}
# This will write a non-terminating error
function NonTerminatingErrorExample { [CmdletBinding()] Param($i = 5) if ($i -gt 4) { Write-Error "I expected a value less or equal to 4!" } Write-Host "However, I can still continue the execution"
}If you're curious as to why I used [CmdletBinding()] in the functions, it's because without that, functions don't support [<CommonParameters>], and -ErrorAction Stop is a CommonParameter.
Now we can wrap them in Try {} Catch {}
# Because the function produces a terminating error, the Catch block will run
Try { TerminatingErrorExample
} Catch { Write-Host "I got you!"
}
# Since the error here is non-terminating, the catch block won't run
Try { NonTerminatingErrorExample
} Catch { Write-Host "You won't see this message"
}
# Now the catch block will run, because we specifically say we want it to stop,
# even on a non-terminating error.
Try { NonTerminatingErrorExample -ErrorAction Stop
} Catch { Write-Host "Now you see this message."
}If we run this, the return will look just like expected:
I got you!
NonTerminatingErrorExample : I expected a value less or equal to 4!
In Zeile:28 Zeichen:5
+ NonTerminatingErrorExample
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,NonTerminatingErrorExample
However, I can still continue the execution
Now you see this message. 2