[英]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_error
即e
是到參考。
throw e;
要重新拋出捕獲的異常,應始終使用不帶表達式的throw。
throw;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.