The Exception class maintains a pointer to an Exception class. This pointer is the cause of the Exception that was thrown. However, if there is no cause, that pointer will point to nothing and upon usage will cause a catastrophe (using a pointer that points to nothing) as with the case below:
Apart from the problem stated above, there is also an issue of the deletion of the pointer to an Exception member.
I believe that my code has memory leaks and holes in them. Could someone please give suggestions for improvement?Exception class is shown below.
[ Exception.hpp ]
[ Exception.cpp ]
Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.
- janvier -
Code:
...
try
{
throw Exception("Ex") ;
}
catch(Exception& e)
{
std::cout << e.what() << std::endl ; // OK
std::cout << e.cause().what() << std::endl ; // points to
nothing: CATASTROPHE!
}
Apart from the problem stated above, there is also an issue of the deletion of the pointer to an Exception member.
I believe that my code has memory leaks and holes in them. Could someone please give suggestions for improvement?Exception class is shown below.
[ Exception.hpp ]
Code:
#ifndef MX_EXCEPTION_H
#define MX_EXCEPTION_H
#include <exception>
#include <string>
class Exception
{
public:
// Constructs a new exception with null message.
Exception(void) ;
// Destructor
virtual ~Exception(void) ;
// Constructs a new exception with the specified message.
Exception(const string& message) ;
// Constructs a new exception with the specified message and cause.
Exception(const string& message, const Exception& cause) ;
// Initializes the cause of this exception.
void initCause(const Exception& cause) ;
// Returns the message of this exception.
const char* what(void) const ;
// Returns the cause of this exception
const Exception& cause(void) const ;
private:
string what_ ;
Exception* cause_ ;
} ;
#endif // MX_EXCEPTION_H
[ Exception.cpp ]
Code:
#include "Exception.hpp"
// Constructs a new exception with null message.
Exception::Exception(void)
{
}
// Destructor
Exception::~Exception(void)
{
}
// Constructs a new exception with the specified message.
Exception::Exception(const string& message) : what_(message)
{
}
// Constructs a new exception with the specified message and cause.
Exception::Exception(const string& message, const Exception& cause) :
what_(message), cause_(new Exception(cause))
{
}
// Initializes the cause of this exception.
void Exception::initCause(const Exception& cause)
{
this->cause_ = new Exception(cause) ;
}
// Returns the message of this exception.
const char* Exception::what(void) const
{
return( what_.c_str() ) ;
}
// Returns the cause of this exception
const Exception& Exception::cause(void) const
{
return ( *cause_ ) ;
}
Rome did not create a great empire by having meetings, they did it by
killing all those who opposed them.
- janvier -