我有一些程序,每次我运行它时,它都会抛出异常,我不知道如何检查它到底抛出了什么,所以我的问题是,是否可以捕获异常并打印它(我发现了抛出异常的行),谢谢提前
发布于 2010-06-19 14:54:40
如果它是从std::exception派生的,你可以通过引用来捕获:
try
{
// code that could cause exception
}
catch (const std::exception &exc)
{
// catch anything thrown within try block that derives from std::exception
std::cerr << exc.what();
}但是如果异常是某个不是从std::exception派生的类,那么您必须提前知道它的类型(即您应该捕获std::string或some_library_exception_base)。
您可以执行“全部捕获”:
try
{
}
catch (...)
{
}但是,你不能对异常做任何事情。
发布于 2016-07-06 17:23:24
在C++11中有:std::current_exception
来自站点的示例代码:
#include <iostream>
#include <string>
#include <exception>
#include <stdexcept>
void handle_eptr(std::exception_ptr eptr) // passing by value is ok
{
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch(const std::exception& e) {
std::cout << "Caught exception \"" << e.what() << "\"\n";
}
}
int main()
{
std::exception_ptr eptr;
try {
std::string().at(1); // this generates an std::out_of_range
} catch(...) {
eptr = std::current_exception(); // capture
}
handle_eptr(eptr);
} // destructor for std::out_of_range called here, when the eptr is destructed发布于 2014-07-28 22:24:21
如果您使用ABI来表示gcc或CLANG,则可以知道未知的异常类型。但这是一个非标准的解决方案。
https://stackoverflow.com/questions/3074646
复制相似问题