178 |
kaklik |
1 |
#ifndef EXCEPTION_H |
|
|
2 |
#define EXCEPTION_H |
|
|
3 |
|
|
|
4 |
#include <exception> |
|
|
5 |
#include <sstream> |
|
|
6 |
#include <string> |
|
|
7 |
|
|
|
8 |
namespace mimas { |
|
|
9 |
|
|
|
10 |
/** Exception class deriving from std::exception. |
|
|
11 |
This class provides a syntax similar to output-streams for convenience. |
|
|
12 |
For compability with other libraries it is inheriting the class |
|
|
13 |
\c std::exception. |
|
|
14 |
|
|
|
15 |
Here is an example how to use an instance of this class (by invoking the |
|
|
16 |
macro MMERROR): |
|
|
17 |
\code |
|
|
18 |
void test( int i ) throw (exception) |
|
|
19 |
{ |
|
|
20 |
MMERROR( i > 0, exception, , |
|
|
21 |
"Parameter for method test must be greater than zero (but was " |
|
|
22 |
<< i << ")." ); |
|
|
23 |
} |
|
|
24 |
|
|
|
25 |
int main(void) |
|
|
26 |
{ |
|
|
27 |
try { |
|
|
28 |
test( -5 ); |
|
|
29 |
} catch ( exception &e ) { |
|
|
30 |
cerr << e.what() << endl; |
|
|
31 |
}; |
|
|
32 |
return 0; |
|
|
33 |
} |
|
|
34 |
\endcode |
|
|
35 |
Mind that the macro uses a variable with the name \c _e. Make sure, that |
|
|
36 |
you don't use this variable-name in any of the macro-arguments! |
|
|
37 |
|
|
|
38 |
@author Jan Wedekind (jan@wedesoft.de) |
|
|
39 |
@date Mon Aug 23 14:37:05 UTC 2004 */ |
|
|
40 |
class mimasexception: public std::exception |
|
|
41 |
{ |
|
|
42 |
public: |
|
|
43 |
/// Constructor. |
|
|
44 |
mimasexception(void) {} |
|
|
45 |
/// Copy constructor. |
|
|
46 |
mimasexception( mimasexception &e ): std::exception( e ) |
|
|
47 |
{ message << e.message.str(); } |
|
|
48 |
/// Destructor. |
|
|
49 |
virtual ~mimasexception(void) throw() {} |
|
|
50 |
/// |
|
|
51 |
template< typename T > |
|
|
52 |
std::ostream &operator<<( const T &t ) { message << t; return message; } |
|
|
53 |
/** Interface for manipulators. |
|
|
54 |
Manipulators such as \c std::endl and \c std::hex use these |
|
|
55 |
functions in constructs like "mimasexception e; e << std::endl". |
|
|
56 |
For more information, see the iomanip header. */ |
|
|
57 |
std::ostream &operator<<( std::ostream& (*__pf)( std::ostream&) ) |
|
|
58 |
{ (*__pf)( message ); return message; } |
|
|
59 |
/// Returns error message (not thread safe). |
|
|
60 |
virtual const char* what(void) const throw() { |
|
|
61 |
temp = message.str(); |
|
|
62 |
return temp.c_str(); |
|
|
63 |
} |
|
|
64 |
protected: |
|
|
65 |
/// Memory-stream containing the error message. |
|
|
66 |
std::ostringstream message; |
|
|
67 |
/** Temporary to do null-termination. |
|
|
68 |
The method \c what() requires a null-terminated string. */ |
|
|
69 |
static std::string temp; |
|
|
70 |
}; |
|
|
71 |
|
|
|
72 |
}; |
|
|
73 |
|
|
|
74 |
#define MMERROR( condition, class, params, message ) \ |
|
|
75 |
if ( !( condition ) ) { \ |
|
|
76 |
class _e params; \ |
|
|
77 |
_e << message; \ |
|
|
78 |
throw _e; \ |
|
|
79 |
}; |
|
|
80 |
|
|
|
81 |
#endif |