]> git.saurik.com Git - wxWidgets.git/blob - samples/except/except.cpp
7d1c9991eb8f511af40d24194840243f28a0d6a4
[wxWidgets.git] / samples / except / except.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/except/except.cpp
3 // Purpose: shows how C++ exceptions can be used in wxWidgets
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 2003-09-17
7 // RCS-ID: $Id$
8 // Copyright: (c) 2003-2005 Vadim Zeitlin
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 #if !wxUSE_EXCEPTIONS
28 #error "This sample only works with wxUSE_EXCEPTIONS == 1"
29 #endif // !wxUSE_EXCEPTIONS
30
31 // for all others, include the necessary headers (this file is usually all you
32 // need because it includes almost all "standard" wxWidgets headers)
33 #ifndef WX_PRECOMP
34 #include "wx/log.h"
35
36 #include "wx/app.h"
37 #include "wx/frame.h"
38 #include "wx/dialog.h"
39 #include "wx/menu.h"
40
41 #include "wx/button.h"
42 #include "wx/sizer.h"
43
44 #include "wx/utils.h"
45 #include "wx/msgdlg.h"
46 #include "wx/icon.h"
47 #endif
48
49 // ----------------------------------------------------------------------------
50 // resources
51 // ----------------------------------------------------------------------------
52
53 // the application icon (under Windows and OS/2 it is in resources)
54 #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__) || defined(__WXMGL__) || defined(__WXX11__)
55 #include "../sample.xpm"
56 #endif
57
58 // ----------------------------------------------------------------------------
59 // private functions
60 // ----------------------------------------------------------------------------
61
62 static void DoCrash()
63 {
64 char *p = 0;
65 strcpy(p, "Let's crash");
66 }
67
68 // ----------------------------------------------------------------------------
69 // private classes
70 // ----------------------------------------------------------------------------
71
72 // Define a new application type, each program should derive a class from wxApp
73 class MyApp : public wxApp
74 {
75 public:
76 // override base class virtuals
77 // ----------------------------
78
79 // program startup
80 virtual bool OnInit();
81
82 // 2nd-level exception handling: we get all the exceptions occuring in any
83 // event handler here
84 virtual bool OnExceptionInMainLoop();
85
86 // 3rd, and final, level exception handling: whenever an unhandled
87 // exception is caught, this function is called
88 virtual void OnUnhandledException();
89
90 // and now for something different: this function is called in case of a
91 // crash (e.g. dereferencing null pointer, division by 0, ...)
92 virtual void OnFatalException();
93 };
94
95 // Define a new frame type: this is going to be our main frame
96 class MyFrame : public wxFrame
97 {
98 public:
99 // ctor(s)
100 MyFrame();
101
102 // event handlers (these functions should _not_ be virtual)
103 void OnQuit(wxCommandEvent& event);
104 void OnAbout(wxCommandEvent& event);
105 void OnDialog(wxCommandEvent& event);
106
107 void OnThrowInt(wxCommandEvent& event);
108 void OnThrowString(wxCommandEvent& event);
109 void OnThrowObject(wxCommandEvent& event);
110 void OnThrowUnhandled(wxCommandEvent& event);
111
112 void OnCrash(wxCommandEvent& event);
113 void OnHandleCrash(wxCommandEvent& event);
114
115 // 1st-level exception handling: we overload ProcessEvent() to be able to
116 // catch exceptions which occur in MyFrame methods here
117 virtual bool ProcessEvent(wxEvent& event);
118
119 private:
120 // any class wishing to process wxWidgets events must use this macro
121 DECLARE_EVENT_TABLE()
122 };
123
124 // A simple dialog which has only some buttons to throw exceptions
125 class MyDialog : public wxDialog
126 {
127 public:
128 MyDialog(wxFrame *parent);
129
130 // event handlers
131 void OnThrowInt(wxCommandEvent& event);
132 void OnThrowObject(wxCommandEvent& event);
133 void OnCrash(wxCommandEvent& event);
134
135 private:
136 DECLARE_EVENT_TABLE()
137 };
138
139 // A trivial exception class
140 class MyException
141 {
142 public:
143 MyException(const wxString& msg) : m_msg(msg) { }
144
145 const wxChar *what() const { return m_msg.c_str(); }
146
147 private:
148 wxString m_msg;
149 };
150
151 // Another exception class which just has to be different from anything else
152 class UnhandledException
153 {
154 };
155
156 // ----------------------------------------------------------------------------
157 // constants
158 // ----------------------------------------------------------------------------
159
160 // IDs for the controls and the menu commands
161 enum
162 {
163 // control ids and menu items
164 Except_ThrowInt = 100,
165 Except_ThrowString,
166 Except_ThrowObject,
167 Except_ThrowUnhandled,
168 Except_Crash,
169 Except_HandleCrash,
170 Except_Dialog,
171
172 Except_Quit = wxID_EXIT,
173 Except_About = wxID_ABOUT
174 };
175
176 // ----------------------------------------------------------------------------
177 // event tables and other macros for wxWidgets
178 // ----------------------------------------------------------------------------
179
180 // the event tables connect the wxWidgets events with the functions (event
181 // handlers) which process them. It can be also done at run-time, but for the
182 // simple menu events like this the static method is much simpler.
183 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
184 EVT_MENU(Except_Quit, MyFrame::OnQuit)
185 EVT_MENU(Except_About, MyFrame::OnAbout)
186 EVT_MENU(Except_Dialog, MyFrame::OnDialog)
187 EVT_MENU(Except_ThrowInt, MyFrame::OnThrowInt)
188 EVT_MENU(Except_ThrowString, MyFrame::OnThrowString)
189 EVT_MENU(Except_ThrowObject, MyFrame::OnThrowObject)
190 EVT_MENU(Except_ThrowUnhandled, MyFrame::OnThrowUnhandled)
191 EVT_MENU(Except_Crash, MyFrame::OnCrash)
192 EVT_MENU(Except_HandleCrash, MyFrame::OnHandleCrash)
193 END_EVENT_TABLE()
194
195 BEGIN_EVENT_TABLE(MyDialog, wxDialog)
196 EVT_BUTTON(Except_ThrowInt, MyDialog::OnThrowInt)
197 EVT_BUTTON(Except_ThrowObject, MyDialog::OnThrowObject)
198 EVT_BUTTON(Except_Crash, MyDialog::OnCrash)
199 END_EVENT_TABLE()
200
201 // Create a new application object: this macro will allow wxWidgets to create
202 // the application object during program execution (it's better than using a
203 // static object for many reasons) and also implements the accessor function
204 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
205 // not wxApp)
206 IMPLEMENT_APP(MyApp)
207
208 // ============================================================================
209 // MyApp implementation
210 // ============================================================================
211
212 // 'Main program' equivalent: the program execution "starts" here
213 bool MyApp::OnInit()
214 {
215 // create the main application window
216 MyFrame *frame = new MyFrame();
217
218 // and show it (the frames, unlike simple controls, are not shown when
219 // created initially)
220 frame->Show(true);
221
222 // success: wxApp::OnRun() will be called which will enter the main message
223 // loop and the application will run. If we returned false here, the
224 // application would exit immediately.
225 return true;
226 }
227
228 bool MyApp::OnExceptionInMainLoop()
229 {
230 try
231 {
232 throw;
233 }
234 catch ( int i )
235 {
236 wxLogWarning(_T("Caught an int %d in MyApp."), i);
237 }
238 catch ( MyException& e )
239 {
240 wxLogWarning(_T("Caught MyException(%s) in MyApp."), e.what());
241 }
242 catch ( ... )
243 {
244 throw;
245 }
246
247 return true;
248 }
249
250 void MyApp::OnUnhandledException()
251 {
252 // this shows how we may let some exception propagate uncaught
253 try
254 {
255 throw;
256 }
257 catch ( UnhandledException& )
258 {
259 throw;
260 }
261 catch ( ... )
262 {
263 wxMessageBox(_T("Unhandled exception caught, program will terminate."),
264 _T("wxExcept Sample"), wxOK | wxICON_ERROR);
265 }
266 }
267
268 void MyApp::OnFatalException()
269 {
270 wxMessageBox(_T("Program has crashed and will terminate."),
271 _T("wxExcept Sample"), wxOK | wxICON_ERROR);
272 }
273
274 // ============================================================================
275 // MyFrame implementation
276 // ============================================================================
277
278 // frame constructor
279 MyFrame::MyFrame()
280 : wxFrame(NULL, wxID_ANY, _T("Except wxWidgets App"),
281 wxPoint(50, 50), wxSize(450, 340))
282 {
283 // set the frame icon
284 SetIcon(wxICON(sample));
285
286 #if wxUSE_MENUS
287 // create a menu bar
288 wxMenu *menuFile = new wxMenu;
289 menuFile->Append(Except_Dialog, _T("Show &dialog\tCtrl-D"));
290 menuFile->AppendSeparator();
291 menuFile->Append(Except_ThrowInt, _T("Throw an &int\tCtrl-I"));
292 menuFile->Append(Except_ThrowString, _T("Throw a &string\tCtrl-S"));
293 menuFile->Append(Except_ThrowObject, _T("Throw an &object\tCtrl-O"));
294 menuFile->Append(Except_ThrowUnhandled,
295 _T("Throw &unhandled exception\tCtrl-U"));
296 menuFile->Append(Except_Crash, _T("&Crash\tCtrl-C"));
297 menuFile->AppendSeparator();
298 menuFile->AppendCheckItem(Except_HandleCrash, _T("&Handle crashes\tCtrl-H"));
299 menuFile->AppendSeparator();
300 menuFile->Append(Except_Quit, _T("E&xit\tCtrl-Q"), _T("Quit this program"));
301
302 wxMenu *helpMenu = new wxMenu;
303 helpMenu->Append(Except_About, _T("&About...\tF1"), _T("Show about dialog"));
304
305 // now append the freshly created menu to the menu bar...
306 wxMenuBar *menuBar = new wxMenuBar();
307 menuBar->Append(menuFile, _T("&File"));
308 menuBar->Append(helpMenu, _T("&Help"));
309
310 // ... and attach this menu bar to the frame
311 SetMenuBar(menuBar);
312 #endif // wxUSE_MENUS
313
314 #if wxUSE_STATUSBAR && !defined(__WXWINCE__)
315 // create a status bar just for fun (by default with 1 pane only)
316 CreateStatusBar(2);
317 SetStatusText(_T("Welcome to wxWidgets!"));
318 #endif // wxUSE_STATUSBAR
319 }
320
321 bool MyFrame::ProcessEvent(wxEvent& event)
322 {
323 try
324 {
325 return wxFrame::ProcessEvent(event);
326 }
327 catch ( const wxChar *msg )
328 {
329 wxLogMessage(_T("Caught a string \"%s\" in MyFrame"), msg);
330
331 return true;
332 }
333 }
334
335 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
336 {
337 // true is to force the frame to close
338 Close(true);
339 }
340
341 void MyFrame::OnDialog(wxCommandEvent& WXUNUSED(event))
342 {
343 try
344 {
345 MyDialog dlg(this);
346
347 dlg.ShowModal();
348 }
349 catch ( ... )
350 {
351 wxLogWarning(_T("An exception in MyDialog"));
352
353 Destroy();
354 throw;
355 }
356 }
357
358 void MyFrame::OnThrowInt(wxCommandEvent& WXUNUSED(event))
359 {
360 throw -17;
361 }
362
363 void MyFrame::OnThrowString(wxCommandEvent& WXUNUSED(event))
364 {
365 throw _T("string thrown from MyFrame");
366 }
367
368 void MyFrame::OnThrowObject(wxCommandEvent& WXUNUSED(event))
369 {
370 throw MyException(_T("Exception thrown from MyFrame"));
371 }
372
373 void MyFrame::OnThrowUnhandled(wxCommandEvent& WXUNUSED(event))
374 {
375 throw UnhandledException();
376 }
377
378 void MyFrame::OnCrash(wxCommandEvent& WXUNUSED(event))
379 {
380 DoCrash();
381 }
382
383 void MyFrame::OnHandleCrash(wxCommandEvent& event)
384 {
385 wxHandleFatalExceptions(event.IsChecked());
386 }
387
388 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
389 {
390 wxString msg;
391 msg.Printf( _T("This is the About dialog of the except sample.\n")
392 _T("Welcome to %s"), wxVERSION_STRING);
393
394 wxMessageBox(msg, _T("About Except"), wxOK | wxICON_INFORMATION, this);
395 }
396
397 // ============================================================================
398 // MyDialog implementation
399 // ============================================================================
400
401 MyDialog::MyDialog(wxFrame *parent)
402 : wxDialog(parent, wxID_ANY, wxString(_T("Throw exception dialog")))
403 {
404 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
405
406 sizerTop->Add(new wxButton(this, Except_ThrowInt, _T("Throw &int")),
407 0, wxCENTRE | wxALL, 5);
408 sizerTop->Add(new wxButton(this, Except_ThrowObject, _T("Throw &object")),
409 0, wxCENTRE | wxALL, 5);
410 sizerTop->Add(new wxButton(this, Except_Crash, _T("&Crash")),
411 0, wxCENTRE | wxALL, 5);
412 sizerTop->Add(new wxButton(this, wxID_CANCEL, _T("&Cancel")),
413 0, wxCENTRE | wxALL, 5);
414
415 SetSizer(sizerTop);
416 sizerTop->Fit(this);
417 }
418
419 void MyDialog::OnThrowInt(wxCommandEvent& WXUNUSED(event))
420 {
421 throw 17;
422 }
423
424 void MyDialog::OnThrowObject(wxCommandEvent& WXUNUSED(event))
425 {
426 throw MyException(_T("Exception thrown from MyDialog"));
427 }
428
429 void MyDialog::OnCrash(wxCommandEvent& WXUNUSED(event))
430 {
431 DoCrash();
432 }
433