trap, scope, and continue

By default, if an error is handled by trap, script execution stops. The continue keyword can be used to resume a script at the next statement.

The following example handles the error raised by throw and continues onto the next statement:

& { 
    Write-Host 'Statement1' 
    throw 'Statement2' 
    Write-Host 'Statement3' 
 
    trap { 
        Write-Host 'An error occurred' 
        continue 
    } 
} 

The behavior of continue is dependent on the scope the trap statement is written in. In the preceding example, continue moves onto writing Statement3 as the trap statement, and the statements being executed are in the same scope.

The following script declares a function that throws an error. trap is declared in the parent scope of the function:

& { 
    function Invoke-Something { 
        Write-Host 'Statement1' 
        throw 'Statement2' 
        Write-Host 'Statement3' 
    } 
 
    Invoke-Something 
    Write-Host 'Done' 
 
    trap { 
        Write-Host 'An error occurred' 
        continue 
    } 
} 

The continue keyword is used, but Statement3 isn't displayed. Execution can only continue in the same scope as the trap statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.202.4