Posted on 2010-04-23 10:54
kongkongzi 阅读(205)
评论(0) 编辑 收藏 引用 所属分类:
c++ programming
1 #include <iostream>
2 #include <string>
3 #include <exception>
4 using namespace std;
5
6
7 class SystemException : public std::exception
8 {
9 public:
10 /// Construct with a specific context and error code.
11 SystemException(const std::string& context, int code)
12 : mContext(context),
13 mCode(code)
14 {
15 }
16 /// Copy constructor.
17 SystemException(const SystemException& e)
18 : std::exception(e),
19 mContext(e.mContext),
20 mCode(e.mCode)
21 {
22 }
23 /// Destructor.
24 virtual ~SystemException() throw ()
25 {
26 }
27 /// Assignment operator.
28 SystemException& operator=(const SystemException& e)
29 {
30 mContext = e.mContext;
31 mCode = e.mCode;
32 return *this;
33 }
34 /// Get a string representation of the exception.
35 virtual const char* what() const throw ()
36 {
37 return mContext.c_str();
38 }
39 /// Get the implementation-defined context associated with the exception.
40 const std::string& Context() const
41 {
42 return mContext;
43 }
44 /// Get the implementation-defined code associated with the exception.
45 int Code() const
46 {
47 return mCode;
48 }
49 private:
50 // The context associated with the error.
51 std::string mContext;
52 // The code associated with the error.
53 int mCode;
54 };
55
56 /// Output the string associated with a system exception.
57 /**
58 * Used to output a human-readable string that is associated with a system
59 * exception.
60 *
61 * @param os The output stream to which the string will be written.
62 *
63 * @param e The exception to be written.
64 *
65 * @return The output stream.
66 *
67 * @relates boost::asio::SystemException
68 */
69 template <typename Ostream>
70 Ostream& operator<<(Ostream& os, const SystemException& e)
71 {
72 os << e.what();
73 return os;
74 }
75
76
77 int main(void)
78 {
79 try
80 {
81 throw SystemException("A system error!", 0);
82 }
83 catch (std::exception& e)
84 {
85 std::cout << "Exception1:" << e.what() << std::endl;
86 }
87 catch (std::string& e)
88 {
89 std::cout << "Exception2:" << e.c_str() << std::endl;
90 }
91 catch ()
92 {
93 std::cout << "catch a exception " << std::endl;
94 }
95
96 std::cout << "end main" << std::endl;
97 return 0;
98 }
99