我们有一个关于 try catch 和 std::runtime_error 的有趣问题。 有人可以向我解释为什么这会返回“未知错误”作为输出吗? 非常感谢您帮助我!
#include "stdafx.h"
#include <iostream>
#include <stdexcept>
int magicCode()
{
throw std::runtime_error("FunnyError");
}
int funnyCatch()
{
try{
magicCode();
} catch (std::exception& e) {
throw e;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
try
{
funnyCatch();
}
catch (std::exception& e)
{
std::cout << e.what();
}
return 0;
}
最佳答案
问题出在这一行。因为带有表达式的 throw
使用该表达式的静态类型来确定抛出的异常,这将异常对象切片构造一个新的 std::exception
对象,仅复制基础对象std::runtime_error
的一部分,e
是对它的引用。
throw e;
要重新抛出捕获的异常,您应该始终使用不带表达式的 throw。
throw;
关于c++ - 将 std::runtime_error 捕获为 std::exception 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3778867/