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;
}
class runtime_error; Defines a type of object to be thrown as exception. It reports errors that are due to events beyond the scope of the program and can not be easily predicted.
Runtime errors don't need to be explicitly caught and handled in code. However, it may be useful to catch them and continue program execution. To handle a runtime error, the code can be placed within a try-catch block and the error can be caught inside the catch block.
Throwing Exceptions runtime_error is a standard pre-defined class whose objects are exceptions. The expression std::runtime_error(message) creates a new runtime_error object, and throw causes it to be immediately “thrown” out of the function, skipping any statements that come afterwards.
I found a perfect response to this problem:
C++ makes an explicit distinction between reference and value copy. Use
catch (const std::exception& e)
to catch by reference instead of value.
Go give upvotes for the original responder here
The problem is with this line. Because throw
with an expression uses the static type of that expression to determine the exception thrown, this slices the exception object constructing a new std::exception
object copying only the base object part of the std::runtime_error
that e
is a reference to.
throw e;
To re-throw the caught exception you should always use throw without an expression.
throw;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With