Categories
User Help

Why “try-catch” does sometimes show errors an sometimes does not? [PowerShell]

Like below with -ErrorAction Stop parameter I successfully catch the error and catch statement showed what I want:

try
{
    Import-Module -ErrorAction Stop -Force nomodule.psm1
}
catch
{
    Write-Host -ForegroundColor Red "no module"

    $PSItem >> $env:HOMEPATH\AVSUB.log
    exit 1
}

If I remove -ErrorAction Stop parameter I got both my message and PS error message. And that is normal.

But in this case below, I didn’t use -ErrorAction Stop parameter and the output like above code. Why sometimes I didn’t need the use -ErrorAction Stop parameter in try-catch?

Problematic code:

 try
    {

    $var= broken_function
}
catch
{
   Write-Host -ForegroundColor Red "error"

    $PSItem >> $env:HOMEPATH\AVSUB.log
    exit 1
}

Leave a Reply

Your email address will not be published. Required fields are marked *