【问题标题】:Does an exception in one statement in a try block cause control flow to bypass any remaining statements in the try block?try 块中的一个语句中的异常是否会导致控制流绕过 try 块中的任何剩余语句?
【发布时间】:2012-10-28 17:30:38
【问题描述】:

我有一些看起来像这样的 C++ 代码:

void Student::addCourse(Course cVal, string gr) throw(...) {
    try {
        GradedCourse c(cVal, gr);  // If an exception is thrown here...
        coursesTaken.insert(c);    // will this statement be executed?
    } catch(...) {
        throw;
    }
}

如果构造函数发现包含课程成绩的gr 无效,则GradedCourse 构造函数可能会抛出异常。如果发生此类异常,是否会执行 try 块内的任何进一步语句?我可以确定这样的异常不会导致尝试将GradedCourse 插入coursesTaken(这是一个 STL 集)吗?我搜索了 Stack Overflow 和 Google,但都没有成功。

【问题讨论】:

  • 是的,如果第一条语句抛出异常,您的第二条语句将永远不会被执行。
  • @HunterMcMillen 如果您想回答问题,为什么不发布答案而不是发表评论?
  • 注意(因为我看到太多了):try/catch/rethrow 是不必要的,throw(...) 规范也是如此...

标签: c++ exception try-catch


【解决方案1】:

没有。

如果GradedCourse c(cVal, gr); 抛出异常,try 块内的任何其他内容都不会被执行。

【讨论】:

  • 哇,我没想到 Stack Overflow 能这么快回答这样的问题……
  • 很高兴您对此感到惊讶;)
【解决方案2】:

现在我明白你想问什么了,但你的标题和问题本身都在问相互矛盾的事情。 :)

如果在 try 块内引发异常,执行将立即跳转到处理该异常的 catch 块,绕过所有其他语句。

Here is the documentation on exceptions. 它并没有直接解决您的问题,但它确实涵盖了其他重要的事情,例如异常嵌套或链接异常处理程序。

【讨论】:

  • 我已经看过链接的文章。如果我需要的信息在那里,我就不会问这个问题了。
猜你喜欢
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多