Feedback on error handling

Hi Don

In “The Big Book of Powershell Error Handling” you have the following code:

ForEach ($computer in $computername) {
    Try {
        $p = Get-Process -Name Notepad -ComputerName $computer
        $ErrorActionPreference = 'Stop'
        $p.Kill()
        $ErrorActionPreference = 'Continue'
    } Catch {
        $computer | Out-File failed.txt -Append
    }
}

I have a question! Should the “$ErrorActionPreference = ‘Continue’” not go in a Finally block?

I ask because if “$p.Kill()” fails it will never be reached.

Thanks.

Alan T

That’s the downside of just pointing people at the Github repository, I suppose. :slight_smile: The error handling book isn’t actually published yet; it’s just a very rough first draft (hence the InProg_ at the beginning of its name.)

You’re right about placing that statement in a finally block, although in this case, you really don’t need to change $ErrorActionPreference at all. Any exceptions thrown by calling a .NET method are already considered terminating errors by PowerShell, and will be caught by a try/catch construct regardless of EAP’s setting (even if it’s SilentlyContinue.)

You can test this as follows:

$ErrorActionPreference = 'SilentlyContinue'

try
{
    [System.IO.File]::Open('c:\bogus\does\not\exist.txt')
}
catch
{
    Write-Host "Caught a terminating error!"
}

$ErrorActionPreference = 'Continue'

Hi Dave

I understand that the setting of the $ErrorActionPreference is not required. I was simply highlighting an issue I thought I saw in the book. Giving an opportunity to discuss it before the book is released.

If I was going to use $ErrorActionPreference I think I would put the “$ErrorActionPreference = ‘Continue’” in a finally block as it could be that the catch exits the script. That said, due to scoping, if I’m exiting the script it might be relevant.

try
{
throw “an error”
}
catch
{
write-host $_
break
}
finally
{
write-host “got here”
}

In the above example the “got here” is output even though the catch exits the script.

Alan

The book is not only “not done,” it’s not even CLOSE. It’s incredibly in-progress, and literally shouldn’t be read.

Hi Don

Sorry, with you posting a link to the repo I thought you wanted feedback.

I’ll await the final release.

Thanks.

Alan

No problem. It’s just that the repo is also a place for authors to collaborate, and right now the error handling book is “on hold” pending me getting time to work on it.