簡體   English   中英

將std :: runtime_error捕獲為std :: exception時出錯

[英]Error with catching std::runtime_error as std::exception

我們在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_errore是到參考。

throw e;

要重新拋出捕獲的異常,應始終使用不帶表達式的throw。

throw;

我找到了對這個問題的完美回應:

C ++明確區分了引用和值復制。 使用

catch (const std::exception& e) 

通過引用而不是值來捕獲。

在這里給原始響應者放棄投票

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM