Fixed include directory name.
[libsex.git] / libsex / Exception.cxx
blobcba2cc67a77b906d9767c2b6aa4eecd7034c0767
1 /**
2 * @file
4 * Definition of @ref libsex::Exception.
5 */
7 #include <libsex/Exception.hxx>
8 #include <cstring> // strncpy()
10 libsex::Exception::Exception(const char* const message)
11 throw()
12 : _previous(0)
14 _initMessage(message);
17 libsex::Exception::Exception(
18 const char* const message,
19 const Exception& previous)
20 throw()
21 : _previous(0)
23 _initMessage(message);
24 try {
25 _previous = previous.clone();
26 } catch (std::bad_alloc& e) {
27 // We need to know the amount of characters
28 // that can be put into _message.
30 // Size to begin with:
31 unsigned int length = Exception::LENGTH;
32 // Substract characters written so far:
33 length -= strlen(_message);
34 // Substract nullbyte appended by strcat().
35 // Prevent underflow.
36 if (length > 0) --length;
38 // Add notice to our original message:
39 strncat(_message, "\n"
40 "std::bad_alloc while cloning Exception!",
41 length);
45 libsex::Exception::~Exception()
46 throw()
48 if (_previous) delete _previous;
51 void libsex::Exception::write(std::ostream& out) const
52 throw(std::ios_base::failure)
54 out << what();
57 void libsex::Exception::backtrace(std::ostream& out) const
58 throw(std::ios_base::failure)
60 write(out);
61 if (_previous != 0) {
62 out << "\n";
63 _previous->backtrace(out);
67 const libsex::Exception* libsex::Exception::clone() const
68 throw(std::bad_alloc)
70 if (_previous) {
71 return new Exception(_message, *_previous);
72 } else {
73 return new Exception(_message);
77 const char* libsex::Exception::what() const
78 throw()
80 return _message;
83 void libsex::Exception::_initMessage(const char* const message)
85 strncpy(_message, message, Exception::LENGTH);
86 // if |message| < |_message|
87 // strncpy() will pad with 0
88 // else
89 // strncpy() will NOT add a trailing 0!
90 _message[Exception::LENGTH] = 0;