Reputation: 113
I have a C++ application with the following source code:
if(!sortedTypedPoints.empty() && sortedTypedPoints[0].type!=PointType::START_VERTEX)
{
throw std::runtime_error("First point in the vector should be a start vertex. Point type: " + sortedTypedPoints[0].type);
}
Note: sortedTypedPoints[0].type is an 'enum'. When the exception occurs, the application is stopped and an incomplete message is displayed in console:
terminate called after throwing an instance of 'std::runtime_error'
what(): rst point in the vector should be a start vertex. Point type:
Aborted (core dumped)
Do you know why the exception message is not displayed entirely (first word is not complete and enum value is not displayed) ?
Upvotes: 1
Views: 72
Reputation: 16843
You cannot concatenate enums to string in c++.
If sortedTypedPoints[0].type
is enum, you may add numeric representation of the enum using to_string:
throw std::runtime_error("First point in the vector should be a start vertex. "
"Point type: " + std::to_string(sortedTypedPoints[0].type));
Or, you may write your own function to convert enums to strings:
std::string to_str(PointType type)
{
switch (type)
{
case PointType::START_VERTEX:
return "START_VERTEX";
case ...:
return "...";
}
return "unknown";
}
and then use this function:
throw std::runtime_error("First point in the vector should be a start vertex. "
"Point type: " + to_str(sortedTypedPoints[0].type));
You may as well use C preprocessor to help you write to_str
function:
std::string to_str(PointType type)
{
#define T(t) if (type==PointType::t) return #t
T(START_VERTEX);
T(END_VERTEX);
T(...);
return "unknown";
#undef T
}
Upvotes: 0
Reputation: 37587
Adding integral value to string literal does not produce string with concatenated integral value text. It actually performs pointer arithmetic calculation instead like this:
char const * psz_error_message{"First point in the vector should be a start vertex. Point type: "};
throw std::runtime_error(psz_error_message + static_cast< int >(sortedTypedPoints[0].type));
To convert enum value to string you need to write your own conversion function. And if you are throwing exception it would be better to create your own exception class that will have type
field so you can store type of your sorted point there for further inspection instead of performing string formatting when throwing.
Upvotes: 0
Reputation: 18817
You are calling the +
on a const char*
and an integer type. This will simply shift the start of your string to the right.
If you have C++11 support, try
".... Point type: " + std::to_string(sortedTypedPoints[0].type)
Upvotes: 2