gpt4 book ai didi

Powershell tr​​y/catch rethrow 不传播错误(Powershell 2.0)

转载 作者:行者123 更新时间:2023-12-02 07:49:45 27 4
gpt4 key购买 nike

我在 try-catch 语句中有一个 try-catch 语句。内层catch捕获错误,但out catch语句中throw并没有导致错误被捕获。 Breifly,我的脚本格式类似于:

$ErrorPreference = "Stop"

try
{
getStuffFromDB

putStuffInDB
}
catch
{
write-host ("Error: " + $error[0])
}

function getStuffFromDB
{
try
{
-- database query statement
}
catch
{
throw
}
finally
{
close connection and clean up
}
}

function putStuffInDB
{
try
{
-- database insert statements statement
}
catch
{
throw
}
finally
{
close connection and clean up
}
}

当我运行脚本时没有出现任何错误,但我注意到我尝试填充的 SQL Server 数据库缺少数据。当我在调试中重新运行脚本时,函数“putStuffInDB”有一个在 catch block 中被捕获的错误。但是当我踩到消息时,它并没有“抛出”到外部 catch block ,而是处理了 finally block 并终止了。

我显然遗漏了一些我没有看到的东西。我过去在 C# 中使用过该构造,并且从未遇到过将错误“传递”到外部 catch block 的问题。

最佳答案

我没有看到这种行为。我在 PowerShell ISE 中运行了以下命令,它产生了预期的结果。数据库中的错误有没有可能实际上没有作为异常抛出?例如,我相信在 SQL Server 中,给定错误级别下的某些错误不会作为异常返回给 ADO.NET 提供程序。

$ErrorActionPreference = 'Stop'

function Throw1 {
try {
Write-Host "Throw1.Try"
throw "Error from Throw1"
}
catch {
Write-Host "Throw1.Catch"
throw
}
finally {
Write-Host "Throw1.Finally"
}
}

function Throw2 {
try {
Write-Host "Throw2.Try"
throw "Error from Throw2"
}
catch {
Write-Host "Throw2.Catch"
throw
}
finally {
Write-Host "Throw2.Finally"
}
}

function Test {
try {
Throw1
Throw2
}
catch {
Write-Host $error[0]
}
}

Test

产生以下内容:

Throw1.Try
Throw1.Catch
Throw1.Finally
Error from Throw1

关于Powershell tr​​y/catch rethrow 不传播错误(Powershell 2.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4456863/

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