我做一个简单的抛出“测试抛出”它没有被我的catch (std::异常& e)。是因为我正在抓一个std::异常& e?我的意思是,只有从 std::exception 派生的异常类才会被捕获吗?如果不是,是我做错了什么还是正常的?顺便说一句,两个 catch 块都没有捕获到 throw 异常。
int main()
{
try
{
throw "TEST THROW"; // TEST
Core core;
core.Init();
core.Load();
while (!core.requestCloseWindow)
{
core.HandleInput();
core.Update();
core.Draw();
}
core.Unload();
core.window->close();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
try
{
time_t rawTime;
struct tm* timeInfo;
char timeBuffer [80];
time(&rawTime);
timeInfo = localtime(&rawTime);
strftime(timeBuffer, 80, "%F %T", timeInfo);
puts(timeBuffer);
std::ofstream ofs; // Pas besoin de close, car le destructeur le fait.
ofs.exceptions(std::ofstream::failbit | std::ofstream::badbit);
ofs.open("log.txt", std::ofstream::out | std::ofstream::app);
ofs << e.what() << std::endl;
}
catch (std::exception& e)
{
std::cerr << "An error occured while writing to a log file!" << std::endl;
}
}
return 0;
}
人们可能会遇到这个问题的另一个原因,特别是如果他们最近一直在编写 Java,那就是他们可能会抛出指向异常的指针.
/* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */
try {
throw new std::runtime_error("catch me");
} catch (std::runtime_error &err) {
std::cerr << "exception caught and ignored: " << err.what() << std::end;
}
/* WARNING WARNING THIS CODE IS WRONG DO NOT COPY */
will not赶上std::runtime_error*
你扔了。它可能会因调用而死亡std::terminate
对于未捕获的异常。
不要分配异常new
,只需按值抛出构造函数,例如
try {
/* note: no 'new' here */
throw std::runtime_error("catch me");
} catch (std::runtime_error &err) {
std::cerr << "exception caught and ignored: " << err.what() << std::end;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)