]> git.saurik.com Git - wxWidgets.git/blob - samples/except/except.cpp
Only link with libwxscintilla if using Scintilla is enabled.
[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
48 #include "wx/thread.h"
49 #endif
50
51 // ----------------------------------------------------------------------------
52 // resources
53 // ----------------------------------------------------------------------------
54
55 // the application icon (under Windows and OS/2 it is in resources)
56 #ifndef wxHAS_IMAGES_IN_RESOURCES
57 #include "../sample.xpm"
58 #endif
59
60 // ----------------------------------------------------------------------------
61 // private functions
62 // ----------------------------------------------------------------------------
63
64 static void DoCrash()
65 {
66 char *p = 0;
67 strcpy(p, "Let's crash");
68 }
69
70 // ----------------------------------------------------------------------------
71 // private classes
72 // ----------------------------------------------------------------------------
73
74 // Define a new application type, each program should derive a class from wxApp
75 class MyApp : public wxApp
76 {
77 public:
78 // override base class virtuals
79 // ----------------------------
80
81 // program startup
82 virtual bool OnInit();
83
84 // 2nd-level exception handling: we get all the exceptions occurring in any
85 // event handler here
86 virtual bool OnExceptionInMainLoop();
87
88 // 3rd, and final, level exception handling: whenever an unhandled
89 // exception is caught, this function is called
90 virtual void OnUnhandledException();
91
92 // and now for something different: this function is called in case of a
93 // crash (e.g. dereferencing null pointer, division by 0, ...)
94 virtual void OnFatalException();
95
96 // you can override this function to do something different (e.g. log the
97 // assert to file) whenever an assertion fails
98 virtual void OnAssertFailure(const wxChar *file,
99 int line,
100 const wxChar *func,
101 const wxChar *cond,
102 const wxChar *msg);
103 };
104
105 // Define a new frame type: this is going to be our main frame
106 class MyFrame : public wxFrame
107 {
108 public:
109 // ctor(s)
110 MyFrame();
111
112 // event handlers (these functions should _not_ be virtual)
113 void OnQuit(wxCommandEvent& event);
114 void OnAbout(wxCommandEvent& event);
115 void OnDialog(wxCommandEvent& event);
116
117 void OnThrowInt(wxCommandEvent& event);
118 void OnThrowString(wxCommandEvent& event);
119 void OnThrowObject(wxCommandEvent& event);
120 void OnThrowUnhandled(wxCommandEvent& event);
121
122 void OnCrash(wxCommandEvent& event);
123 void OnTrap(wxCommandEvent& event);
124 #if wxUSE_ON_FATAL_EXCEPTION
125 void OnHandleCrash(wxCommandEvent& event);
126 #endif
127
128 protected:
129
130 // 1st-level exception handling: we overload ProcessEvent() to be able to
131 // catch exceptions which occur in MyFrame methods here
132 virtual bool ProcessEvent(wxEvent& event);
133
134 // provoke assert in main or worker thread
135 //
136 // this is used to show how an assert failure message box looks like
137 void OnShowAssert(wxCommandEvent& event);
138 #if wxUSE_THREADS
139 void OnShowAssertInThread(wxCommandEvent& event);
140 #endif // wxUSE_THREADS
141
142 private:
143 // any class wishing to process wxWidgets events must use this macro
144 DECLARE_EVENT_TABLE()
145 };
146
147 // A simple dialog which has only some buttons to throw exceptions
148 class MyDialog : public wxDialog
149 {
150 public:
151 MyDialog(wxFrame *parent);
152
153 // event handlers
154 void OnThrowInt(wxCommandEvent& event);
155 void OnThrowObject(wxCommandEvent& event);
156 void OnCrash(wxCommandEvent& event);
157
158 private:
159 DECLARE_EVENT_TABLE()
160 };
161
162 // A trivial exception class
163 class MyException
164 {
165 public:
166 MyException(const wxString& msg) : m_msg(msg) { }
167
168 const wxChar *what() const { return m_msg.c_str(); }
169
170 private:
171 wxString m_msg;
172 };
173
174 // Another exception class which just has to be different from anything else
175 class UnhandledException
176 {
177 };
178
179 // ----------------------------------------------------------------------------
180 // constants
181 // ----------------------------------------------------------------------------
182
183 // IDs for the controls and the menu commands
184 enum
185 {
186 // control ids and menu items
187 Except_ThrowInt = wxID_HIGHEST,
188 Except_ThrowString,
189 Except_ThrowObject,
190 Except_ThrowUnhandled,
191 Except_Crash,
192 Except_Trap,
193 #if wxUSE_ON_FATAL_EXCEPTION
194 Except_HandleCrash,
195 #endif // wxUSE_ON_FATAL_EXCEPTION
196 Except_ShowAssert,
197 #if wxUSE_THREADS
198 Except_ShowAssertInThread,
199 #endif // wxUSE_THREADS
200 Except_Dialog,
201
202 Except_Quit = wxID_EXIT,
203 Except_About = wxID_ABOUT
204 };
205
206 // ----------------------------------------------------------------------------
207 // event tables and other macros for wxWidgets
208 // ----------------------------------------------------------------------------
209
210 // the event tables connect the wxWidgets events with the functions (event
211 // handlers) which process them. It can be also done at run-time, but for the
212 // simple menu events like this the static method is much simpler.
213 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
214 EVT_MENU(Except_Quit, MyFrame::OnQuit)
215 EVT_MENU(Except_About, MyFrame::OnAbout)
216 EVT_MENU(Except_Dialog, MyFrame::OnDialog)
217 EVT_MENU(Except_ThrowInt, MyFrame::OnThrowInt)
218 EVT_MENU(Except_ThrowString, MyFrame::OnThrowString)
219 EVT_MENU(Except_ThrowObject, MyFrame::OnThrowObject)
220 EVT_MENU(Except_ThrowUnhandled, MyFrame::OnThrowUnhandled)
221 EVT_MENU(Except_Crash, MyFrame::OnCrash)
222 EVT_MENU(Except_Trap, MyFrame::OnTrap)
223 #if wxUSE_ON_FATAL_EXCEPTION
224 EVT_MENU(Except_HandleCrash, MyFrame::OnHandleCrash)
225 #endif // wxUSE_ON_FATAL_EXCEPTION
226 EVT_MENU(Except_ShowAssert, MyFrame::OnShowAssert)
227 #if wxUSE_THREADS
228 EVT_MENU(Except_ShowAssertInThread, MyFrame::OnShowAssertInThread)
229 #endif // wxUSE_THREADS
230 END_EVENT_TABLE()
231
232 BEGIN_EVENT_TABLE(MyDialog, wxDialog)
233 EVT_BUTTON(Except_ThrowInt, MyDialog::OnThrowInt)
234 EVT_BUTTON(Except_ThrowObject, MyDialog::OnThrowObject)
235 EVT_BUTTON(Except_Crash, MyDialog::OnCrash)
236 END_EVENT_TABLE()
237
238 // Create a new application object: this macro will allow wxWidgets to create
239 // the application object during program execution (it's better than using a
240 // static object for many reasons) and also implements the accessor function
241 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
242 // not wxApp)
243 IMPLEMENT_APP(MyApp)
244
245 // ============================================================================
246 // MyApp implementation
247 // ============================================================================
248
249 // 'Main program' equivalent: the program execution "starts" here
250 bool MyApp::OnInit()
251 {
252 if ( !wxApp::OnInit() )
253 return false;
254
255 // create the main application window
256 MyFrame *frame = new MyFrame();
257
258 // and show it (the frames, unlike simple controls, are not shown when
259 // created initially)
260 frame->Show(true);
261
262 // success: wxApp::OnRun() will be called which will enter the main message
263 // loop and the application will run. If we returned false here, the
264 // application would exit immediately.
265 return true;
266 }
267
268 bool MyApp::OnExceptionInMainLoop()
269 {
270 try
271 {
272 throw;
273 }
274 catch ( int i )
275 {
276 wxLogWarning(wxT("Caught an int %d in MyApp."), i);
277 }
278 catch ( MyException& e )
279 {
280 wxLogWarning(wxT("Caught MyException(%s) in MyApp."), e.what());
281 }
282 catch ( ... )
283 {
284 throw;
285 }
286
287 return true;
288 }
289
290 void MyApp::OnUnhandledException()
291 {
292 // this shows how we may let some exception propagate uncaught
293 try
294 {
295 throw;
296 }
297 catch ( UnhandledException& )
298 {
299 throw;
300 }
301 catch ( ... )
302 {
303 wxMessageBox(wxT("Unhandled exception caught, program will terminate."),
304 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
305 }
306 }
307
308 void MyApp::OnFatalException()
309 {
310 wxMessageBox(wxT("Program has crashed and will terminate."),
311 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
312 }
313
314 void MyApp::OnAssertFailure(const wxChar *file,
315 int line,
316 const wxChar *func,
317 const wxChar *cond,
318 const wxChar *msg)
319 {
320 // take care to not show the message box from a worker thread, this doesn't
321 // work as it doesn't have any event loop
322 if ( !wxIsMainThread() ||
323 wxMessageBox
324 (
325 wxString::Format("An assert failed in %s().", func) +
326 "\n"
327 "Do you want to call the default assert handler?",
328 "wxExcept Sample",
329 wxYES_NO | wxICON_QUESTION
330 ) == wxYES )
331 {
332 wxApp::OnAssertFailure(file, line, func, cond, msg);
333 }
334 }
335
336 // ============================================================================
337 // MyFrame implementation
338 // ============================================================================
339
340 // frame constructor
341 MyFrame::MyFrame()
342 : wxFrame(NULL, wxID_ANY, wxT("Except wxWidgets App"),
343 wxPoint(50, 50), wxSize(450, 340))
344 {
345 // set the frame icon
346 SetIcon(wxICON(sample));
347
348 #if wxUSE_MENUS
349 // create a menu bar
350 wxMenu *menuFile = new wxMenu;
351 menuFile->Append(Except_Dialog, wxT("Show &dialog\tCtrl-D"));
352 menuFile->AppendSeparator();
353 menuFile->Append(Except_ThrowInt, wxT("Throw an &int\tCtrl-I"));
354 menuFile->Append(Except_ThrowString, wxT("Throw a &string\tCtrl-S"));
355 menuFile->Append(Except_ThrowObject, wxT("Throw an &object\tCtrl-O"));
356 menuFile->Append(Except_ThrowUnhandled,
357 wxT("Throw &unhandled exception\tCtrl-U"));
358 menuFile->Append(Except_Crash, wxT("&Crash\tCtrl-C"));
359 menuFile->Append(Except_Trap, "&Trap\tCtrl-T",
360 "Break into the debugger (if one is running)");
361 menuFile->AppendSeparator();
362 #if wxUSE_ON_FATAL_EXCEPTION
363 menuFile->AppendCheckItem(Except_HandleCrash, wxT("&Handle crashes\tCtrl-H"));
364 menuFile->AppendSeparator();
365 #endif // wxUSE_ON_FATAL_EXCEPTION
366 menuFile->Append(Except_ShowAssert, wxT("Provoke &assert failure\tCtrl-A"));
367 #if wxUSE_THREADS
368 menuFile->Append(Except_ShowAssertInThread,
369 wxT("Assert failure in &thread\tShift-Ctrl-A"));
370 #endif // wxUSE_THREADS
371 menuFile->AppendSeparator();
372 menuFile->Append(Except_Quit, wxT("E&xit\tCtrl-Q"), wxT("Quit this program"));
373
374 wxMenu *helpMenu = new wxMenu;
375 helpMenu->Append(Except_About, wxT("&About\tF1"), wxT("Show about dialog"));
376
377 // now append the freshly created menu to the menu bar...
378 wxMenuBar *menuBar = new wxMenuBar();
379 menuBar->Append(menuFile, wxT("&File"));
380 menuBar->Append(helpMenu, wxT("&Help"));
381
382 // ... and attach this menu bar to the frame
383 SetMenuBar(menuBar);
384 #endif // wxUSE_MENUS
385
386 #if wxUSE_STATUSBAR && !defined(__WXWINCE__)
387 // create a status bar just for fun (by default with 1 pane only)
388 CreateStatusBar(2);
389 SetStatusText(wxT("Welcome to wxWidgets!"));
390 #endif // wxUSE_STATUSBAR
391 }
392
393 bool MyFrame::ProcessEvent(wxEvent& event)
394 {
395 try
396 {
397 return wxFrame::ProcessEvent(event);
398 }
399 catch ( const wxChar *msg )
400 {
401 wxLogMessage(wxT("Caught a string \"%s\" in MyFrame"), msg);
402
403 return true;
404 }
405 }
406
407 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
408 {
409 // true is to force the frame to close
410 Close(true);
411 }
412
413 void MyFrame::OnDialog(wxCommandEvent& WXUNUSED(event))
414 {
415 try
416 {
417 MyDialog dlg(this);
418
419 dlg.ShowModal();
420 }
421 catch ( ... )
422 {
423 wxLogWarning(wxT("An exception in MyDialog"));
424
425 Destroy();
426 throw;
427 }
428 }
429
430 void MyFrame::OnThrowInt(wxCommandEvent& WXUNUSED(event))
431 {
432 throw -17;
433 }
434
435 void MyFrame::OnThrowString(wxCommandEvent& WXUNUSED(event))
436 {
437 throw wxT("string thrown from MyFrame");
438 }
439
440 void MyFrame::OnThrowObject(wxCommandEvent& WXUNUSED(event))
441 {
442 throw MyException(wxT("Exception thrown from MyFrame"));
443 }
444
445 void MyFrame::OnThrowUnhandled(wxCommandEvent& WXUNUSED(event))
446 {
447 throw UnhandledException();
448 }
449
450 void MyFrame::OnCrash(wxCommandEvent& WXUNUSED(event))
451 {
452 DoCrash();
453 }
454
455 void MyFrame::OnTrap(wxCommandEvent& WXUNUSED(event))
456 {
457 wxTrap();
458 }
459
460 #if wxUSE_ON_FATAL_EXCEPTION
461
462 void MyFrame::OnHandleCrash(wxCommandEvent& event)
463 {
464 wxHandleFatalExceptions(event.IsChecked());
465 }
466
467 #endif // wxUSE_ON_FATAL_EXCEPTION
468
469 void MyFrame::OnShowAssert(wxCommandEvent& WXUNUSED(event))
470 {
471 // provoke an assert from wxArrayString
472 wxArrayString arr;
473 arr[0];
474 }
475
476 #if wxUSE_THREADS
477
478 void MyFrame::OnShowAssertInThread(wxCommandEvent& WXUNUSED(event))
479 {
480 class AssertThread : public wxThread
481 {
482 public:
483 AssertThread()
484 : wxThread(wxTHREAD_JOINABLE)
485 {
486 }
487
488 protected:
489 virtual void *Entry()
490 {
491 wxFAIL_MSG("Test assert in another thread.");
492
493 return 0;
494 }
495 };
496
497 AssertThread thread;
498 thread.Create();
499 thread.Run();
500 thread.Wait();
501 }
502
503 #endif // wxUSE_THREADS
504
505 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
506 {
507 wxString msg;
508 msg.Printf( wxT("This is the About dialog of the except sample.\n")
509 wxT("Welcome to %s"), wxVERSION_STRING);
510
511 wxMessageBox(msg, wxT("About Except"), wxOK | wxICON_INFORMATION, this);
512 }
513
514 // ============================================================================
515 // MyDialog implementation
516 // ============================================================================
517
518 MyDialog::MyDialog(wxFrame *parent)
519 : wxDialog(parent, wxID_ANY, wxString(wxT("Throw exception dialog")))
520 {
521 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
522
523 sizerTop->Add(new wxButton(this, Except_ThrowInt, wxT("Throw &int")),
524 0, wxCENTRE | wxALL, 5);
525 sizerTop->Add(new wxButton(this, Except_ThrowObject, wxT("Throw &object")),
526 0, wxCENTRE | wxALL, 5);
527 sizerTop->Add(new wxButton(this, Except_Crash, wxT("&Crash")),
528 0, wxCENTRE | wxALL, 5);
529 sizerTop->Add(new wxButton(this, wxID_CANCEL, wxT("&Cancel")),
530 0, wxCENTRE | wxALL, 5);
531
532 SetSizerAndFit(sizerTop);
533 }
534
535 void MyDialog::OnThrowInt(wxCommandEvent& WXUNUSED(event))
536 {
537 throw 17;
538 }
539
540 void MyDialog::OnThrowObject(wxCommandEvent& WXUNUSED(event))
541 {
542 throw MyException(wxT("Exception thrown from MyDialog"));
543 }
544
545 void MyDialog::OnCrash(wxCommandEvent& WXUNUSED(event))
546 {
547 DoCrash();
548 }
549