new sample showing how to handle exceptions in wxWindows code
[wxWidgets.git] / samples / except / except.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: except.cpp
3 // Purpose: Except wxWindows sample
4 // Author: Julian Smart
5 // Modified by:
6 // Created: 04/01/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Julian Smart
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 // for all others, include the necessary headers (this file is usually all you
28 // need because it includes almost all "standard" wxWindows headers)
29 #ifndef WX_PRECOMP
30 #include "wx/app.h"
31 #include "wx/frame.h"
32 #include "wx/dialog.h"
33
34 #include "wx/button.h"
35 #include "wx/sizer.h"
36
37 #include "wx/utils.h" // for wxMessageBox
38 #endif
39
40 // ----------------------------------------------------------------------------
41 // resources
42 // ----------------------------------------------------------------------------
43
44 // the application icon (under Windows and OS/2 it is in resources)
45 #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__) || defined(__WXMGL__) || defined(__WXX11__)
46 #include "../sample.xpm"
47 #endif
48
49 // ----------------------------------------------------------------------------
50 // private classes
51 // ----------------------------------------------------------------------------
52
53 // Define a new application type, each program should derive a class from wxApp
54 class MyApp : public wxApp
55 {
56 public:
57 // override base class virtuals
58 // ----------------------------
59
60 // program startup
61 virtual bool OnInit();
62
63 // 2nd-level exception handling: we get all the exceptions occuring in any
64 // event handler here
65 virtual void HandleEvent(wxEvtHandler *handler,
66 wxEventFunction func,
67 wxEvent& event) const;
68
69 // 3rd, and final, level exception handling: whenever an unhandled
70 // exception is caught, this function is called
71 virtual void OnUnhandledException();
72 };
73
74 // Define a new frame type: this is going to be our main frame
75 class MyFrame : public wxFrame
76 {
77 public:
78 // ctor(s)
79 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size,
80 long style = wxDEFAULT_FRAME_STYLE);
81
82 // event handlers (these functions should _not_ be virtual)
83 void OnQuit(wxCommandEvent& event);
84 void OnAbout(wxCommandEvent& event);
85 void OnDialog(wxCommandEvent& event);
86 void OnThrowString(wxCommandEvent& event);
87
88 // 1st-level exception handling: we overload ProcessEvent() to be able to
89 // catch exceptions which occur in MyFrame methods here
90 virtual bool ProcessEvent(wxEvent& event);
91
92 private:
93 // any class wishing to process wxWindows events must use this macro
94 DECLARE_EVENT_TABLE()
95 };
96
97 // A simple dialog which has only some buttons to throw exceptions
98 class MyDialog : public wxDialog
99 {
100 public:
101 MyDialog(wxFrame *parent);
102
103 // event handlers
104 void OnThrowInt(wxCommandEvent& event);
105 void OnThrowObject(wxCommandEvent& event);
106
107 private:
108 DECLARE_EVENT_TABLE()
109 };
110
111 // A trivial exception class
112 class MyException
113 {
114 public:
115 MyException(const wxString& msg) : m_msg(msg) { }
116
117 const wxChar *what() const { return m_msg.c_str(); }
118
119 private:
120 wxString m_msg;
121 };
122
123 // ----------------------------------------------------------------------------
124 // constants
125 // ----------------------------------------------------------------------------
126
127 // IDs for the controls and the menu commands
128 enum
129 {
130 // control ids
131 Except_ThrowInt = 100,
132 Except_ThrowObject,
133
134 // menu items
135 Except_ThrowString = 200,
136 Except_Dialog,
137
138 Except_Quit = wxID_EXIT,
139 Except_About = wxID_ABOUT
140 };
141
142 // ----------------------------------------------------------------------------
143 // event tables and other macros for wxWindows
144 // ----------------------------------------------------------------------------
145
146 // the event tables connect the wxWindows events with the functions (event
147 // handlers) which process them. It can be also done at run-time, but for the
148 // simple menu events like this the static method is much simpler.
149 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
150 EVT_MENU(Except_Quit, MyFrame::OnQuit)
151 EVT_MENU(Except_About, MyFrame::OnAbout)
152 EVT_MENU(Except_Dialog, MyFrame::OnDialog)
153 EVT_MENU(Except_ThrowString, MyFrame::OnThrowString)
154 END_EVENT_TABLE()
155
156 BEGIN_EVENT_TABLE(MyDialog, wxDialog)
157 EVT_BUTTON(Except_ThrowInt, MyDialog::OnThrowInt)
158 EVT_BUTTON(Except_ThrowObject, MyDialog::OnThrowObject)
159 END_EVENT_TABLE()
160
161 // Create a new application object: this macro will allow wxWindows to create
162 // the application object during program execution (it's better than using a
163 // static object for many reasons) and also implements the accessor function
164 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
165 // not wxApp)
166 IMPLEMENT_APP(MyApp)
167
168 // ============================================================================
169 // MyApp implementation
170 // ============================================================================
171
172 // 'Main program' equivalent: the program execution "starts" here
173 bool MyApp::OnInit()
174 {
175 // create the main application window
176 MyFrame *frame = new MyFrame(_T("Except wxWindows App"),
177 wxPoint(50, 50), wxSize(450, 340));
178
179 // and show it (the frames, unlike simple controls, are not shown when
180 // created initially)
181 frame->Show(true);
182
183 // success: wxApp::OnRun() will be called which will enter the main message
184 // loop and the application will run. If we returned false here, the
185 // application would exit immediately.
186 return true;
187 }
188
189 void
190 MyApp::HandleEvent(wxEvtHandler *handler,
191 wxEventFunction func,
192 wxEvent& event) const
193 {
194 try
195 {
196 wxApp::HandleEvent(handler, func, event);
197 }
198 catch ( int i )
199 {
200 wxLogError(_T("Caught an int %d in MyApp."), i);
201 }
202 }
203
204 void MyApp::OnUnhandledException()
205 {
206 wxMessageBox(_T("Unhandled exception caught, program will terminate."),
207 _T("wxExcept Sample"), wxOK | wxICON_ERROR);
208 }
209
210 // ============================================================================
211 // MyFrame implementation
212 // ============================================================================
213
214 // frame constructor
215 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size, long style)
216 : wxFrame(NULL, -1, title, pos, size, style)
217 {
218 // set the frame icon
219 SetIcon(wxICON(mondrian));
220
221 #if wxUSE_MENUS
222 // create a menu bar
223 wxMenu *menuFile = new wxMenu;
224 menuFile->Append(Except_Dialog, _T("Show &dialog\tCtrl-D"));
225 menuFile->Append(Except_ThrowString, _T("Throw a &string\tCtrl-S"));
226 menuFile->AppendSeparator();
227 menuFile->Append(Except_Quit, _T("E&xit\tCtrl-Q"), _T("Quit this program"));
228
229 wxMenu *helpMenu = new wxMenu;
230 helpMenu->Append(Except_About, _T("&About...\tF1"), _T("Show about dialog"));
231
232 // now append the freshly created menu to the menu bar...
233 wxMenuBar *menuBar = new wxMenuBar();
234 menuBar->Append(menuFile, _T("&File"));
235 menuBar->Append(helpMenu, _T("&Help"));
236
237 // ... and attach this menu bar to the frame
238 SetMenuBar(menuBar);
239 #endif // wxUSE_MENUS
240
241 #if wxUSE_STATUSBAR && !defined(__WXWINCE__)
242 // create a status bar just for fun (by default with 1 pane only)
243 CreateStatusBar(2);
244 SetStatusText(_T("Welcome to wxWindows!"));
245 #endif // wxUSE_STATUSBAR
246 }
247
248 bool MyFrame::ProcessEvent(wxEvent& event)
249 {
250 try
251 {
252 return wxFrame::ProcessEvent(event);
253 }
254 catch ( const wxChar *msg )
255 {
256 wxLogMessage(_T("Caught a string \"%s\" in MyFrame"), msg);
257
258 return true;
259 }
260 }
261
262 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
263 {
264 // true is to force the frame to close
265 Close(true);
266 }
267
268 void MyFrame::OnDialog(wxCommandEvent& WXUNUSED(event))
269 {
270 MyDialog dlg(this);
271
272 dlg.ShowModal();
273 }
274
275 void MyFrame::OnThrowString(wxCommandEvent& WXUNUSED(event))
276 {
277 throw _T("some string");
278 }
279
280 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
281 {
282 wxString msg;
283 msg.Printf( _T("This is the About dialog of the except sample.\n")
284 _T("Welcome to %s"), wxVERSION_STRING);
285
286 wxMessageBox(msg, _T("About Except"), wxOK | wxICON_INFORMATION, this);
287 }
288
289 // ============================================================================
290 // MyDialog implementation
291 // ============================================================================
292
293 MyDialog::MyDialog(wxFrame *parent)
294 : wxDialog(parent, -1, wxString(_T("Throw exception dialog")))
295 {
296 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
297
298 sizerTop->Add(new wxButton(this, Except_ThrowInt, _T("Throw &int")),
299 0, wxCENTRE | wxALL, 5);
300 sizerTop->Add(new wxButton(this, Except_ThrowObject, _T("Throw &object")),
301 0, wxCENTRE | wxALL, 5);
302 sizerTop->Add(new wxButton(this, wxID_CANCEL, _T("&Cancel")),
303 0, wxCENTRE | wxALL, 5);
304
305 SetSizer(sizerTop);
306 sizerTop->Fit(this);
307 }
308
309 void MyDialog::OnThrowInt(wxCommandEvent& WXUNUSED(event))
310 {
311 throw 17;
312 }
313
314 void MyDialog::OnThrowObject(wxCommandEvent& WXUNUSED(event))
315 {
316 throw MyException(_T("Exception thrown from the dialog"));
317 }
318