2 * Shows how this framework is supposed to be used.
5 // Needed for the tests in this file, not part of the
7 #include <tests/src/UsageExamples.hxx>
11 // This is the way to declare an exception class.
12 // --- Start MyException.hxx ---
14 #ifndef MYEXCEPTION_HXX
15 #define MYEXCEPTION_HXX
17 #include <source/declare.hxx>
18 #include <source/Exception.hxx>
20 // MyException inherits from libsex::Exception.
21 LIBSEX_DECLARE(libsex::Exception
, MyException
)
25 // --- End MyException.hxx ---
29 // This is the way to define an exception class.
30 // --- Start MyException.cxx ---
32 #include <source/define.hxx>
33 #include <source/Exception.hxx>
34 // You need to include its header file (MyException.hxx)!
36 // Define MyException and provide a message template (see
37 // printf for a list of placeholders).
39 // This is the file to localize.
40 LIBSEX_DEFINE(libsex::Exception
, MyException
, "%s is %d")
42 // --- End MyException.cxx ---
46 // Lets create an exception with a fixed message:
47 LIBSEX_DECLARE(libsex::Exception
, Error
)
48 LIBSEX_DEFINE(libsex::Exception
, Error
, "Error!")
51 #include <source/throw.hxx> // THROW and CHAIN
54 * How to simply create an exception.
56 void UsageExamples::testSimpleConstruction()
59 std::string
msg("Someone has set us up the bomb!");
61 // Create an exception, do not throw it. Note we
62 // can pass any string as message.
63 MyException
e(msg
.c_str());
65 // Turn exception's description into an instance of
66 // std::string (needed for comparing).
67 std::string
what(e
.what());
71 CPPUNIT_ASSERT_EQUAL(msg
, what
);
75 * How to throw a single exception without placeholders in
76 * its message template.
78 void UsageExamples::testSimpleThrowing()
83 // Create an instance and throw it.
84 // Note that THROW uses the message
85 // template, so we can not pass an
89 std::string
exp(__FILE__
); exp
+= ":87: Error!";
90 std::string
act(e
.what());
92 CPPUNIT_ASSERT_EQUAL(exp
, act
);
96 CPPUNIT_ASSERT(success
);
100 * How to throw a single exception.
102 void UsageExamples::testThrowing()
104 bool success
= false;
107 // Fill the parameters into the message
108 // template and throw an exception
109 // containing the resulting string.
110 THROW(MyException
, "foobar", 42);
111 } catch (MyException
& e
) {
112 std::string
exp(__FILE__
); exp
+= ":110: foobar is 42";
113 std::string
act(e
.what());
115 CPPUNIT_ASSERT_EQUAL(exp
, act
);
119 CPPUNIT_ASSERT(success
);
123 * How to chain exceptions.
125 void UsageExamples::testChaining()
127 bool success
= false;
131 THROW(MyException
, "foo", 21);
132 } catch (MyException
& e
) {
133 // Note that the variable name in
134 // the catch clause must be e for
135 // the CHAIN macro to function.
136 CHAIN(MyException
, "bar", 42);
138 } catch (MyException
& e
) {
139 std::string
exp(__FILE__
);
140 exp
+= ":136: bar is 42\n";
142 exp
+= ":131: foo is 21";
144 std::stringstream act
;
147 CPPUNIT_ASSERT_EQUAL(
154 CPPUNIT_ASSERT(success
);