views:

587

answers:

4

Currently, I have this code to prepend a "tag" to an exception message which gives me a very light version of a stack trace:

try {
    doSomething();
} catch (std::exception& e) {
    int size = 8 + _tcslen(e.what());
    TCHAR* error = new TCHAR[size];
    _sntprintf(error, size, TEXT("myTag: %s"), e.what());
    std::exception x = std::exception(error);
    delete []error;
    throw x;
}

It just looks horrible and I'm sure that there has to be an easy way to accomplish this. Could you please help me with this?

+2  A: 

what about something like this:

throw std::exception(std::string("myTag: ").append(e.what()).c_str());

Added a call to c_str() and tested it in Visual Studio and it works (side note: this doesn't compile in gcc, there's only a default constructor in the implementation).

Idan K
thanks! (feeling stupid that I've thinked about it for nearly an hour without ever thinking about the std::string....)
Etan
A: 

Yeah, there is.

std::string S1="Hello",S2=" World";
S1+=S2;
Aviral Dasgupta
A: 

Why don't you directly use std::string. You can do std::string s = std::string("myTag") + e.what(). And if you want char* pointer use c_str() member function of string.

Naveen
+3  A: 

Why don't you use std::string?

try {
    doSomething();
} catch (const std::exception& e)
{
    throw std::exception(std::string("myTag: ") + e.what());
}

Other notes: To my knowledge std::exception does not have this form of constructor (only its subclasses do).

Not sure why you are using a TCHAR buffer. Can std::exception::what ever return anything but char*? If so, perhaps you can use std::basic_string<TCHAR>.

Important thing to keep in mind: what returns a const char* (for whatever reason). For example, it has left be wondering where the 10 or 13 characters have disappeared:

throw some_exception(e.what() + '\n' + moreinfo);
UncleBens
you are correct. std::exception returns a `virtual const char*`.
Etan
@fnieto: Are you downvoting _me_ because OP uses this non-standard constructor, and I even commented on it? As to not using const, I guess it is a force of habit (I actually can't remember seeing any piece of code catching it by const reference in tutorials).
UncleBens
+1 to counter the downvote..this is a perfectly valid answer.
Naveen
@Naveen. Added the const if it makes you happy. But my psychic powers are failing me and I couldn't tell which exception type OP wants to throw instead.
UncleBens