I'm trying to write an exception class that needs to be thrown when a system call fails. The exception should have a developer message and the errno code, and it's what
method should format the developer message along with the error code. The C way to do the formatting is snprintf
, but I'm trying to avoid that. I tried defining a class member for the exception of type std::stringstream
. However, that did not work since stringstream
has a private copy constructor. Looking for an alternative I learned about Boost's format object. I tried using it and got a different error:
In file included from tun_device.cc:7:0:
system_error.h:9:7: error: looser throw specifier for ‘virtual SystemError::~SystemError()’
class SystemError : public exception
^
In file included from system_error.h:4:0,
from tun_device.cc:7:
/usr/include/c++/4.8/exception:64:13: error: overriding ‘virtual std::exception::~exception() throw ()’
virtual ~exception() _GLIBCXX_USE_NOEXCEPT;
The way to solve this was to define my own destructor:
~SystemError() throw() {
}
As I understand, this line specifies that the destructor of this exception should not throw any exceptions.
Here's the complete class:
class SystemError : public exception
{
public:
int m_errno;
const char * m_message;
SystemError(int err, const char * message) :
fmt("%1%: %2%") {
fmt % message % errno;
m_errno = err;
this->m_message = message;
}
const char * what() const throw(){
return fmt.str().c_str();
}
~SystemError() throw() {
}
private:
format fmt;
};
I have several questions:
First of all - Am I reinventing the wheel? Is already there a recommended C++ way to handle failed system calls?
Why does using the
format
class as a member of the exception forces me to override the default destructor?Is there any pitfall I should be aware of now that I added my own destructor?
Is there a way to achieve what I want using only the standard C++ library?