简体   繁体   中英

Powershell error handling

Take the below example.

Function Test-Function {
    try {
        [int]$var.ToString()
    }catch{
        Write-Error "Error inside Function"     
    }
}


try {
    Test-Function
}catch{
    Write-Error "Error inside try/catch of script"
}

Test-Function itself is generating an error (on purpose in this case, to test this behaviour), therefore hitting it's own catch. However, the Function call itself within the script, is also wrapped in a Try Catch statement, but the script only ever displays the catch of the function. Is this behaviour by design?

The answer is how try - catch works and what Write-Error does. From Doc.Microsoft we know that....

The Write-Error cmdlet declares a non-terminating error

And looking at About_Try_Catch_Finally we see that it...

Describes how to use the Try, Catch, and Finally blocks to handle terminating errors.

Emphasis mine in both quotes

Try catch is not going to capture the output from Write-Error and that is by design. If you want to pass a terminating error use throw

Function Test-Function {
    try {
        [int]$var1.ToString()
    }catch{
        throw "Error inside Function"     
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM