在try catch块中未捕获异常
Exception not caught in try catch block
我做了一个简单的抛出"TEST throw ",它不会在我的catch (std::exception&e) 。是因为我正在捕捉一个std::exception&吗?我的意思是,只有从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;
}
人们可能遇到这个问题的另一个原因,特别是如果他们最近一直在编写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 */
将不能接住你扔的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;
}
你在扔一个const char*
。std::exception
只捕获std::exception
及其所有派生类。所以为了接住你的投掷,你应该投掷std::runtime_error("TEST THROW")
代替。或std::logic_error("TEST THROW")
;随便什么更合适。下面列出了std::exception
的派生类
可以添加抓住(…)
当你抛出一个继承类型的异常,但是继承是私有的
由于这不是MCVE (Core
是什么?),我不能明确地解决这个问题,但您肯定错过了
#include <exception>
实际上,即使没有包含,GCC也会编译,但是异常不会被捕获,您将以
结束。抛出'std::exception'实例后终止调用
(): std::异常
。/{program}: {PID} Aborted (core dump)
相关文章:
- 当类定义不可见时捕获异常
- 来自 Android 应用程序内部的 boost 类型的 boost::wrapexcept<boost::system::system_error> 的未捕获异常
- 如何通过 pybind11 从 python 中的C++中捕获异常?
- 有没有更好的方法来处理异常? try-catch块真的很丑
- 信号后未捕获异常
- 捕获异常后如何退出程序执行
- C++ 捕获异常后进行清理的标准方法是什么?
- 使用模板类引发和捕获异常
- E/libc++abi:终止于类型为google::protobuf::FatalException的未捕获异常
- 如果在生成 std::thread 后引发,则未捕获异常
- C++ 未捕获异常,程序将终止并中止
- C++程序在第一次尝试时会给出垃圾,但如果它捕获异常并重试,则会给出适当的值
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 如何捕获 I/O 异常(确切地说是 I/O,而不是 std::exception)
- 为什么捕获异常播放允许尾括号
- throw() 函数应该总是在异常时展开堆栈并允许捕获异常还是必须调用 std::terminate ?
- 寻求与类型为 std::invalid_argument 的未捕获异常相关的运行时错误的建议: stoi:无转换
- Try-Catch 未捕获异常
- try和catch块没有捕获异常,而是将结果作为无穷大
- 在try catch块中未捕获异常