Error Types

suggest change

PowerShell errors fall into two groups:

A terminating error stops the current command. A non-terminating error lets the command keep going to the next statement.

That is true when $ErrorActionPreference is the default, Continue. $ErrorActionPreference is a preference variable that tells PowerShell what to do with a non-terminating error.

Terminating error

A terminating error can be handled with a typical try catch, as below

Try
{
    Write-Host "Attempting Divide By Zero"
    1/0
}
Catch
{
    Write-Host "A Terminating Error: Divide by Zero Caught!" 
}

The snippet runs, and the catch block handles the error. In PowerShell, dividing by zero is a terminating error.

Non-Terminating Error

A non-terminating error, on the other hand, is not caught by catch by default. PowerShell does not treat it as a critical error.

Try
{
    Stop-Process -Id 123456
}
Catch
{
    Write-Host "Non-Terminating Error: Invalid Process ID"
}

If you run the example above, the catch block does not run, because the error is not terminating. Execution continues with the next command, and the error is still displayed. To handle a non-terminating error in catch, turn it into a terminating error.

Try
{
    Stop-Process -Id 123456 -ErrorAction Stop
}
Catch
{
    "Non-Terminating Error: Invalid Process ID"
}

Now, with the updated Error preference, this error will be considered a Terminating error and will be caught in the catch block.

Invoking Terminating & Non-Terminating Errors:

Write-Error writes a non-terminating error and does not stop execution. throw raises a terminating error and stops the current scope:

Write-host "Going to try a non terminating Error "
Write-Error "Non terminating" 
Write-host "Going to try a terminating Error "
throw "Terminating Error " 
Write-Host "This line won't be displayed"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents