c++ - 在 C++ 中抛出表达式重新排序?

标签 c++ exception

在 C++ 中,两个 throw 表达式,或者围绕 throw 表达式的表达式可以重新排序吗?

例如,在下面的代码中:

int f(int x) {
  if (! (x >= 0))
    throw std::range_error("argument must be non-negative");
  return pure_sqrt(x);
}

inf g(int y) {
  if (! (y > 0))
    throw std::range_error("argument must be positive");
  return pure_invsqrt(y);
}

void test(int x, int y) {
  try {
    int a = f(x);
    int b = g(y);
    return a + b;
  } catch (std::exception e) {
    std::cout << "Error: " << e.what() << "." << std::endl;
  }
}

假设 x == -1y == -1,可以从 g 中排除异常(“argument must be positive” ) 在 f 的异常之前抛出?

也就是说,纯函数(除了它们的抛出行为)是否可以重新排序,或者未捕获的异常是否被 try block 的其余部分视为可观察的行为?

最佳答案

没有。当 f 抛出时,执行在 catch block 中继续。 g 永远不会执行。

关于c++ - 在 C++ 中抛出表达式重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46866260/

相关文章:

c++ - 使用辅助数组的C++比较器排序

c++ - 我应该避免哪些 C++ 陷阱?

java - tinyradius 验证方法导致 NullPointerException

c++ - 在共享库中增加异常

android - 如何将 .cpp 包含文件添加到 android.mk 中的依赖项?

c++ - 在多个线程之间安全地共享一个结构

Java : Unknown error in exception handling

Java Css html到pdf转换异常发现无效的嵌套标签头,预期的结束标签链接

delphi - 记录后我应该如何重新引发 Delphi 异常?

c++ - 子对象上的 ostream 获取其父对象的 ostream