将std :: runtime_error捕获为std :: exception时出错

Blu*_*rin 7 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;
}
Run Code Online (Sandbox Code Playgroud)

CB *_*ley 19

问题出在这条线上.因为throw表达式使用该表达式的静态类型来确定抛出的异常,所以这个异常对象构造一个新std::exception对象,只复制std::runtime_error那个e引用的基础对象部分.

throw e;
Run Code Online (Sandbox Code Playgroud)

要重新抛出捕获的异常,应始终使用不带表达式的throw.

throw;
Run Code Online (Sandbox Code Playgroud)

  • 快了18秒......他是怎么做到的? (2认同)