c++ - 将 std::runtime_error 捕获为 std::exception 时出错

标签 c++ exception try-catch

我们有一个关于 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/

相关文章:

c++ - 当真正释放STL中的内存时

.net - 神秘的WPF异常: 'PresentationFramework.Eren Vista'

Java SE 窗口显示 "Not Responing"。我的 try/catch 有问题吗?

javascript - 如何在使用 window.onerror 处理语句 1 的错误时继续语句 2

java - 确定导致 Google Dataflow 作业失败的特定输入数据

c++ - 使用双链表的电话簿

c++ - 替代大型数据集的 vector ? C++

c# - 正则表达式:找到整数但不是 float

java - 在没有捕获的 try/catch/finally 中会发生什么?

java - rawsql 中的关系运算符无效,相同的语句在 sqldeveloper 中有效