use*_*866 2 powershell rethrow
我在 try-catch 语句中有一个 try-catch 语句。内部 catch 捕获错误,但 throw 不会导致错误在 out catch 语句中被捕获。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
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行脚本时没有错误,但我注意到我试图填充的 SQL Server 数据库丢失了数据。当我在调试中重新运行脚本时,函数“putStuffInDB”有一个错误,该错误被捕获在 catch 块中。但是当我步进时,消息没有被“抛出”到外部 catch 块,而是处理了 finally 块并终止了。
我显然错过了一些我没有看到的东西。我过去曾在 C# 中使用过该构造,并且从未遇到过将错误“传递”到外部 catch 块的问题。
我没有看到这种行为。我在 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
Run Code Online (Sandbox Code Playgroud)
产生以下内容:
Throw1.Try
Throw1.Catch
Throw1.Finally
Error from Throw1
Run Code Online (Sandbox Code Playgroud)