gpt4 book ai didi

powershell - Powershell陷阱和处理中的功能错误

转载 作者:行者123 更新时间:2023-12-03 08:26:17 25 4
gpt4 key购买 nike

如何在不传播函数至主要函数的情况下处理函数中的错误?

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

结果是:
subroutine caught error
main caught it too!
Attempted to divide by zero.
...

我希望子例程处理它自己的错误,并且我不想更改全局错误处理设置 $ErrorActionPreference或依靠用户设置 -ErrorAction参数。

最佳答案

通过continue语句交换break语句:

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

如果那还不够的话,我会尝试使用try/catch,因为@ reSTLess1987受到了欢迎。

Windows IT Pro 很好地描述了陷阱。

关于powershell - Powershell陷阱和处理中的功能错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40561161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com