【问题标题】:Powershell jumps into finally without exception messagePowershell 无异常跳转到 finally 消息
【发布时间】:2012-08-10 13:14:35
【问题描述】:

我的 PowerShell 代码有问题。有时——无论出于何种原因——我的脚本直接跳到 finally 块中,而没有来自 catch 块的任何错误消息。这是我的 PowerShell 代码:

try
{
    $sleepTime = $reservationDuration - $prepareTime
    (get-date -format hh:mm:ss)+"`tinfo:`tstart sleep before warning VIP sleep-time:"+$sleepTime | out-file $logFilePath -append
    start-sleep -s $sleepTime
    (get-date -format hh:mm:ss)+"`tinfo:`tsleeptime over" | out-file $logFilePath -append
}
catch
{
    (get-date -format hh:mm:ss)+"`terror:`tchaught exception: "+$error[0] | out-file $logFilePath -append
}


finally{
    (get-date -format hh:mm:ss)+"`tinfo:`tFinally" | out-file $logFilePath -append
}

如您所见,我正在编写一些日志文件以查看发生了什么。我总是在我的 $sleepTime 变量中得到正确的 int 值。但是有时它会直接跳到 finally 块中而没有写“sleeptime over..”甚至“chaught exception...”

【问题讨论】:

    标签: powershell exception-handling try-catch-finally


    【解决方案1】:

    catch 块执行的唯一时间是在 try 块中出现异常时。您在 try 块中所做的唯一有可能产生异常的事情就是写入日志文件。

    所以catch块只会在有异常阻止输出写入日志文件时才会执行。

    如果我遗漏了什么,请告诉我。

    【讨论】:

    • 我认为他的问题的重点是sometimes it jumps right into the finally block without writing "sleeptime over.." or even "chaught exception...",这意味着他的'Finally'语句被写入日志,但trycatch都没有,暗示因为try没有不要写,catch 应该有,但它没有。
    • @SpellingD 这确实使问题更有意义。在提供的示例代码中,我看不到如何跳过 try 块。我注意到有变量 $reservationDuration$prepareTime 从未使用值初始化,所以看起来我们没有查看完整的脚本。
    • 很抱歉这个难以理解的问题。好吧,我确实省略了一些代码以使其更具可读性。 $sleepTime 计算前面有一些方法。但我想——因为我的第一个日志文件写入方法“tinfo:`tstart sleep before warning VIP sleep-time:”工作之前的代码就可以了。您提到的变量之前刚刚初始化。或者可能是由于 $ErrorActionPreference = Continue 属性而出现异常并且仍然​​写入日志文件,然后程序跳转写入 finally 语句?
    • 是的,看起来就是这个问题。我发现 stackoverflow.com/questions/3097785 解释了 try/catch 只能捕获终止错误。您可能遇到了文件使用中的错误,这是一个非终止错误。我认为您的问题将通过将out-file $logFilePath -append 更改为out-file $logFilePath -append -ea stop 来解决。
    猜你喜欢
    • 2012-05-11
    • 1970-01-01
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2020-03-12
    相关资源
    最近更新 更多