we have a funny problem with try catch and std::runtime_error.
Can someone explain to me why this is returning “Unknown error” as output ?
Thanks very 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;
}
The problem is with this line. Because
throwwith an expression uses the static type of that expression to determine the exception thrown, this slices the exception object constructing a newstd::exceptionobject copying only the base object part of thestd::runtime_errorthateis a reference to.To re-throw the caught exception you should always use throw without an expression.