BlueTrin
BlueTrin

Reputation: 10063

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;
}

Upvotes: 9

Views: 21334

Answers (2)

umlimo
umlimo

Reputation: 61

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

Upvotes: 1

CB Bailey
CB Bailey

Reputation: 791551

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;

Upvotes: 24

Related Questions