9

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;
}
1
  • It prints "FunnyError" for me, using Visual C++ 2010. Which compiler are you using? Commented Sep 23, 2010 at 13:36

2 Answers 2

24

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;
Sign up to request clarification or add additional context in comments.

7 Comments

18 seconds faster ... how does he do it ?!
Ah, exception's copy constructor doesn't have to preserve what(). I didn't realise that.
Charles, I thought that throw e; would call the copy constructor std::exception(const std::exception e), which would create a correct copy of the exception ? Is it not the case ?
Yes, it uses std::exception's copy constructor. No, this won't necessarily result in a 'correct' copy of the exception as std::exception is only the base class of the exception that e actually refers to.
Thank you for the complete answer, I have been taught to always rethrow using throw, while investigating an issue, I was curious about why the message returned by what() was not preserved. Thanks to you I know the reason, Charles !
|
1

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

1 Comment

I didn't catch by value copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.