Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error with 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 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;
}
like image 353
BlueTrin Avatar asked Sep 23 '10 13:09

BlueTrin


People also ask

What is Runtime_error in exception handling?

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.

How do you catch a run time error?

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.

How do you throw a runtime error exception in C++?

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.


2 Answers

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

like image 159
umlimo Avatar answered Oct 07 '22 14:10

umlimo


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;
like image 21
CB Bailey Avatar answered Oct 07 '22 14:10

CB Bailey