Error catching std :: runtime_error as std :: exception

We have a funny problem with try catch and std :: runtime_error. Can someone explain to me why this returns "Unknown error" as output? Thanks so much for helping me!

#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;
}
+5
source share
2 answers

The problem is this line. Since throwthe expression uses the static type of this expression to determine the exception thrown, this cuts the exception object, creating a new object std::exceptionthat copies only part of the base object std::runtime_error, which eis a reference to.

throw e;

catch, throw .

throw;
+17

:

++ .

catch (const std::exception& e) 

.

, upvotes

0

All Articles