我做了一个简单的抛出"TEST THROW"并没有捕到我的catch(std :: exception&e).是因为我正在捕捉一个std :: exception&e?我的意思是,只有从std :: exception派生的异常类才被捕获?如果没有,我做错了什么还是正常的?顺便说一下,两个catch块都没有捕获抛出异常.
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;
Run Code Online (Sandbox Code Playgroud)
}
人们可能会遇到这个问题的另一个原因,特别是如果他们最近一直在编写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 */
Run Code Online (Sandbox Code Playgroud)
会不会赶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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4448 次 |
| 最近记录: |