Marc
Marc

Reputation: 14294

Powershell Trap and Handle Error in Function

How can I handle errors in a function without propagating it up to the main function?

function main() {
    trap {
        "main caught it too!"
    }
    subroutine
}
function subroutine() {
    trap {
        "subroutine caught error"
        Break
    }
    1/0
}
main

Results in:

subroutine caught error
main caught it too!
Attempted to divide by zero.
...

I want subroutine to handle it's own error and I don't want to change global error handling settings $ErrorActionPreference or rely on the user to set an -ErrorAction parameter.

Upvotes: 0

Views: 768

Answers (3)

restless1987
restless1987

Reputation: 1598

trap does not handle the error completely - it still passes them through. You can use try\catch for that:

function main() {
try {
    subroutine
}
catch{
    "main caught it too!"
}
}
function subroutine() {
try {
    1/0
}
catch{
    "subroutine caught error"
    Break
}
}
main

Upvotes: 0

Marc
Marc

Reputation: 14294

It seems the answer to what I wanted: exit the subroutine without propagating the error further is Return:

function main() {
    trap {
        "main caught it too!" # Will not happen
    }
    subroutine
}
function subroutine() {
    trap {
        "subroutine caught error"
        Return
    }
    1/0
    "this will not execute"
}
main

Output:

subroutine caught error

Upvotes: 0

Moerwald
Moerwald

Reputation: 11294

Exchange the break statement through a continue statement:

function main() {
     trap {
         "main caught it too!"
     }
     subroutine
}

function subroutine() {
     trap {
         "subroutine caught error"
         continue
     }
     1/0; Write-host "I was executed after the ERROR"
}
main
subroutine caught error
I was executed after the ERROR

If that is not enough I would go with try/catch as @restless1987 sugested.

Windows IT Pro gives a nice description about trap.

Upvotes: 1

Related Questions