【问题标题】:How do I exit from a try-catch block in PowerShell?如何退出 PowerShell 中的 try-catch 块?
【发布时间】:2012-11-03 17:18:38
【问题描述】:

我想从try 块内退出:

function myfunc
{
   try {
      # Some things
      if(condition) { 'I want to go to the end of the function' }
      # Some other things
   }
   catch {
      'Whoop!'
   }

   # Other statements here
   return $whatever
}

我用break 进行了测试,但这不起作用。如果任何调用代码在循环内,它会中断上层循环。

【问题讨论】:

  • 我相信只有 VB.net 有“退出尝试”。虽然下面的脚本块技巧相当聪明!

标签: powershell try-catch


【解决方案1】:

围绕try/catch 和其中的return 的额外脚本块可能会这样做:

function myfunc($condition)
{
    # Extra script block, use `return` to exit from it
    .{
        try {
            'some things'
            if($condition) { return }
            'some other things'
        }
        catch {
            'Whoop!'
        }
    }
    'End of try/catch'
}

# It gets 'some other things' done
myfunc

# It skips 'some other things'
myfunc $true

【讨论】:

  • 不错的把戏(因为是的,这是个把戏)。为什么在第一个大括号之前使用点?我没有测试过,看起来也不错。
  • 如果没有点它不应该工作(在这种情况下,函数创建并输出脚本块)。点运算符调用当前范围内的脚本。还有&。它可用于在新范围内调用(例如,为了对函数的其余部分隐藏一些内部变量)。
  • 至于 trick...好吧,PowerShell 本身并没有提供任何退出 try/catch 的功能。
  • 'if($condition) { return }' 有什么问题?,似乎对我有用
  • @Shay Levy - 这将是“从整个函数返回”,而不是“到 try/catch 的末尾”。
【解决方案2】:

做你想做的事的规范方法是否定条件并将“其他事情”放入“then”块中。

function myfunc {
  try {
    # some things
    if (-not condition) {
      # some other things
    }
  } catch {
    'Whoop!'
  }

  # other statements here
  return $whatever
}

【讨论】:

  • 不,因为我可能有几个点要退出“尝试”块。
  • 你应该在你的问题中提到这一点。此外,这可以通过嵌套额外的if-statements 来实现。更不用说try/catch 块并不是你真正“退出”的东西。尝试这样做(多次不少于)就像是在尝试解决问题,而不是修复损坏的程序逻辑。
  • 这已经在第一句话和标题中完美提及:“我想从 try 块中退出”。第一个答案已经(几乎)完美了。
  • FTR:你确实没有提到anywhere你想退出的地方不止一个,不是在第一句话中,也不是在标题中,而不是在您的代码示例中。我提供了一个干净的解决方案。你可以忽略它。
  • “我想从 try 块中退出”。为什么要找这个破绽?上一个答案完全满足了这一点。它下面的 cmets 确认问题很清楚。
【解决方案3】:

你可以这样做:

function myfunc
{
   try {
      # Some things
      if(condition)
      {
          goto(catch)
      }
      # Some other things
   }
   catch {
      'Whoop!'
   }

   # Other statements here
   return $whatever
}

【讨论】:

  • 我认为 OP 不想触发捕获。我认为他们想完全跳出try-catch之外。但是,如果我没记错的话,您的 goto 可能会使用隐含的 finally {} 块。
  • goto(catch)对我不起作用。 PowerShell 版本 5.1。我收到一条错误消息 The term 'catch' is not recognized as the name of a cmdlet, function, script file, or operable program. 所以我使用“通常”的方式退出尝试:抛出异常 - 这会将我立即带到 catch 块。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-16
  • 2013-11-25
相关资源
最近更新 更多