Reputation: 843
If a system call fails, I would like to throw an exception that contains the 'errno' relating to the failure. Right now, I use this:
if (bind(...) == -1) {
std::stringstream s;
s << "Error:" << errno << " during bind";
throw std::runtime_error(s.str());
}
That seems clumsy. I cannot directly append an integer to an std::string() - what is the best solution for this? Java has String().append(int), but there's no such facility in std::string. Does everyone write a wrapper around std::string for this purpose?
Upvotes: 2
Views: 202
Reputation: 26930
You could write your own:
Here is some hints:
class Exception{
public:
Exception(const char* sourceFile, const char* sourceFunction, int sourceLine, Type type, const char* info = 0, ...);
protected:
const char *mSourceFile;
const char *mSourceFunction;
int mSourceLine;
Type mType;
char mInfo[2048];
};
Where type could be:
enum Type
{
UNSPECIFIED_ERROR, //! Error cause unspecified.
.. other types of error...
};
So you can pass string in the usual format.. e.g.
Exception(__FILE__, __FUNCTION__, __LINE__, Type::UNSPECIFIED_ERROR, "Error %d", myInt);
Upvotes: 2
Reputation: 10720
I like using boost::format
for this.
std::string msg = boost::str( boost::format("Error: %1% during bind") % errno );
throw std::runtime_error(msg);
One caveat is that if you have a bad_alloc
in a catch block, you might hide the previous error. boost::format
uses allocations as far as I know, so it could suffer from this. You aren't catching here, so it doesn't exactly apply. It is something to be aware of with error handling though.
Upvotes: 3
Reputation: 121961
boost::lexical_cast
is useful in this scenario:
throw std::runtime_error("Error:" + boost::lexical_cast<std::string>(errno) + " during bind");
Upvotes: 3