无法捕获 C++ 异常

Can't catch a C++ exception

我想在尝试使用某些 class 的复制构造函数时捕获异常,这会引发异常。

#include <iostream>

class dont_copy_me {
public:
    dont_copy_me() {}
    dont_copy_me(const dont_copy_me& rhs) {throw;}
    dont_copy_me(dont_copy_me&& rhs) {throw;}
    ~dont_copy_me() {}
};

int main() {
    try {
        dont_copy_me obj;
        dont_copy_me obj_1(obj);
    } catch(...) {
        std::cout << "exception caught" << std::endl;
    }
    return 0;
}

但我不断收到

terminate called without an active exception
Aborted (core dumped)

怎么了?如何捕获复制构造函数抛出的异常? (因为这就是我需要的)

居然抛出这样的异常:

#include <iostream>
#include <stdexcept>

class dont_copy_me {
public:
    dont_copy_me() {}
    dont_copy_me(const dont_copy_me& rhs) {throw std::runtime_error("Fail!");}
    dont_copy_me(dont_copy_me&& rhs) {throw std::runtime_error("Fail!");}
    ~dont_copy_me() {}
};

int main() {
    try {
        dont_copy_me obj;
        dont_copy_me obj_1(obj);
    } catch(...) {
        std::cout << "exception caught" << std::endl;
    }
    return 0;
}

这就是您所需要的。 Here 您可以找到标准例外列表(在 "Exception categories" 下)。

throw 表达式仅在您已经在处理活动异常时才有效:

Rethrows the currently handled exception. Abandons the execution of the current catch block and passes control to the next matching exception handler (but not to another catch clause after the same try block: its compound-statement is considered to have been 'exited'), reusing the existing exception object: no new objects are made. This form is only allowed when an exception is presently being handled (it calls std::terminate if used otherwise). The catch clause associated with a function-try-block must exit via rethrowing if used on a constructor.

来自 here,强调我的。

你的 catch (...) 块没问题,问题是你的程序没有抛出异常。

throw表达式有两种形式:

  1. throw <some-exception> 创建并抛出异常
  2. throw 重新抛出 当前 异常

在您的代码中,您从复制构造函数中调用了第二种形式。请改用第一种形式。

第二种形式在您想要对异常进行部分处理时使用。这是一个使用两种形式的人为示例程序:

#include <cstdexcept>
#include <cstdlib>
#include <iostream>

int main()
{
  int ret = EXIT_FAILURE ;
  try
  {
    try
    {
      throw std::logic_error("Fail!"); // form 1
      ret = EXIT_SUCCESS;
    }
    catch (...)
    {
      std::clog << "re-throwing" << std::endl;
      throw; // form 2
    }
  }
  catch (...)
  {
    std::cerr << "unhandled exception" << std::endl;
  }
  return ret;
}

参见:http://en.cppreference.com/w/cpp/language/throw