]> git.saurik.com Git - wxWidgets.git/blame - samples/except/except.cpp
Whack-a-mole with wxOSX/PPC unit tests continued.
[wxWidgets.git] / samples / except / except.cpp
CommitLineData
556b8c1a 1/////////////////////////////////////////////////////////////////////////////
f78e4942
VZ
2// Name: samples/except/except.cpp
3// Purpose: shows how C++ exceptions can be used in wxWidgets
4// Author: Vadim Zeitlin
556b8c1a 5// Modified by:
f78e4942 6// Created: 2003-09-17
556b8c1a 7// RCS-ID: $Id$
f78e4942 8// Copyright: (c) 2003-2005 Vadim Zeitlin
556b8c1a
VZ
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
f78e4942
VZ
27#if !wxUSE_EXCEPTIONS
28 #error "This sample only works with wxUSE_EXCEPTIONS == 1"
29#endif // !wxUSE_EXCEPTIONS
30
556b8c1a 31// for all others, include the necessary headers (this file is usually all you
be5a51fb 32// need because it includes almost all "standard" wxWidgets headers)
556b8c1a 33#ifndef WX_PRECOMP
532c7736
VZ
34 #include "wx/log.h"
35
556b8c1a
VZ
36 #include "wx/app.h"
37 #include "wx/frame.h"
38 #include "wx/dialog.h"
532c7736 39 #include "wx/menu.h"
556b8c1a
VZ
40
41 #include "wx/button.h"
42 #include "wx/sizer.h"
43
30deac1f
WS
44 #include "wx/utils.h"
45 #include "wx/msgdlg.h"
60c474a0 46 #include "wx/icon.h"
2d8e0096
VZ
47
48 #include "wx/thread.h"
556b8c1a
VZ
49#endif
50
51// ----------------------------------------------------------------------------
52// resources
53// ----------------------------------------------------------------------------
54
55// the application icon (under Windows and OS/2 it is in resources)
e7092398 56#ifndef wxHAS_IMAGES_IN_RESOURCES
556b8c1a
VZ
57 #include "../sample.xpm"
58#endif
59
cc9a3957
VZ
60// ----------------------------------------------------------------------------
61// private functions
62// ----------------------------------------------------------------------------
63
64static void DoCrash()
65{
66 char *p = 0;
67 strcpy(p, "Let's crash");
68}
69
556b8c1a
VZ
70// ----------------------------------------------------------------------------
71// private classes
72// ----------------------------------------------------------------------------
73
74// Define a new application type, each program should derive a class from wxApp
75class MyApp : public wxApp
76{
77public:
78 // override base class virtuals
79 // ----------------------------
80
81 // program startup
82 virtual bool OnInit();
83
3103e8a9 84 // 2nd-level exception handling: we get all the exceptions occurring in any
556b8c1a 85 // event handler here
cc9a3957 86 virtual bool OnExceptionInMainLoop();
556b8c1a
VZ
87
88 // 3rd, and final, level exception handling: whenever an unhandled
89 // exception is caught, this function is called
90 virtual void OnUnhandledException();
cc9a3957
VZ
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();
3eeb7e10 95
5cd3213b
VZ
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);
556b8c1a
VZ
103};
104
105// Define a new frame type: this is going to be our main frame
106class MyFrame : public wxFrame
107{
108public:
109 // ctor(s)
cc9a3957 110 MyFrame();
556b8c1a
VZ
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);
cc9a3957
VZ
116
117 void OnThrowInt(wxCommandEvent& event);
556b8c1a 118 void OnThrowString(wxCommandEvent& event);
cc9a3957
VZ
119 void OnThrowObject(wxCommandEvent& event);
120 void OnThrowUnhandled(wxCommandEvent& event);
121
122 void OnCrash(wxCommandEvent& event);
55fd62c1 123 void OnTrap(wxCommandEvent& event);
b6b375a9 124#if wxUSE_ON_FATAL_EXCEPTION
cc9a3957 125 void OnHandleCrash(wxCommandEvent& event);
b6b375a9 126#endif
556b8c1a 127
004867db
FM
128protected:
129
556b8c1a
VZ
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
2d8e0096
VZ
134 // provoke assert in main or worker thread
135 //
136 // this is used to show how an assert failure message box looks like
3eeb7e10 137 void OnShowAssert(wxCommandEvent& event);
2d8e0096
VZ
138#if wxUSE_THREADS
139 void OnShowAssertInThread(wxCommandEvent& event);
140#endif // wxUSE_THREADS
3eeb7e10 141
556b8c1a 142private:
be5a51fb 143 // any class wishing to process wxWidgets events must use this macro
556b8c1a
VZ
144 DECLARE_EVENT_TABLE()
145};
146
147// A simple dialog which has only some buttons to throw exceptions
148class MyDialog : public wxDialog
149{
150public:
151 MyDialog(wxFrame *parent);
152
153 // event handlers
154 void OnThrowInt(wxCommandEvent& event);
155 void OnThrowObject(wxCommandEvent& event);
f78e4942 156 void OnCrash(wxCommandEvent& event);
556b8c1a
VZ
157
158private:
159 DECLARE_EVENT_TABLE()
160};
161
162// A trivial exception class
163class MyException
164{
165public:
166 MyException(const wxString& msg) : m_msg(msg) { }
167
168 const wxChar *what() const { return m_msg.c_str(); }
169
170private:
171 wxString m_msg;
172};
173
cc9a3957
VZ
174// Another exception class which just has to be different from anything else
175class UnhandledException
176{
177};
178
556b8c1a
VZ
179// ----------------------------------------------------------------------------
180// constants
181// ----------------------------------------------------------------------------
182
183// IDs for the controls and the menu commands
184enum
185{
cc9a3957 186 // control ids and menu items
b6b375a9 187 Except_ThrowInt = wxID_HIGHEST,
cc9a3957 188 Except_ThrowString,
556b8c1a 189 Except_ThrowObject,
cc9a3957 190 Except_ThrowUnhandled,
f78e4942 191 Except_Crash,
55fd62c1 192 Except_Trap,
b6b375a9 193#if wxUSE_ON_FATAL_EXCEPTION
cc9a3957 194 Except_HandleCrash,
3eeb7e10 195#endif // wxUSE_ON_FATAL_EXCEPTION
3eeb7e10 196 Except_ShowAssert,
2d8e0096
VZ
197#if wxUSE_THREADS
198 Except_ShowAssertInThread,
199#endif // wxUSE_THREADS
556b8c1a
VZ
200 Except_Dialog,
201
202 Except_Quit = wxID_EXIT,
203 Except_About = wxID_ABOUT
204};
205
206// ----------------------------------------------------------------------------
be5a51fb 207// event tables and other macros for wxWidgets
556b8c1a
VZ
208// ----------------------------------------------------------------------------
209
be5a51fb 210// the event tables connect the wxWidgets events with the functions (event
556b8c1a
VZ
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.
213BEGIN_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)
cc9a3957 217 EVT_MENU(Except_ThrowInt, MyFrame::OnThrowInt)
556b8c1a 218 EVT_MENU(Except_ThrowString, MyFrame::OnThrowString)
cc9a3957
VZ
219 EVT_MENU(Except_ThrowObject, MyFrame::OnThrowObject)
220 EVT_MENU(Except_ThrowUnhandled, MyFrame::OnThrowUnhandled)
221 EVT_MENU(Except_Crash, MyFrame::OnCrash)
55fd62c1 222 EVT_MENU(Except_Trap, MyFrame::OnTrap)
b6b375a9 223#if wxUSE_ON_FATAL_EXCEPTION
cc9a3957 224 EVT_MENU(Except_HandleCrash, MyFrame::OnHandleCrash)
3eeb7e10 225#endif // wxUSE_ON_FATAL_EXCEPTION
3eeb7e10 226 EVT_MENU(Except_ShowAssert, MyFrame::OnShowAssert)
2d8e0096
VZ
227#if wxUSE_THREADS
228 EVT_MENU(Except_ShowAssertInThread, MyFrame::OnShowAssertInThread)
229#endif // wxUSE_THREADS
556b8c1a
VZ
230END_EVENT_TABLE()
231
232BEGIN_EVENT_TABLE(MyDialog, wxDialog)
233 EVT_BUTTON(Except_ThrowInt, MyDialog::OnThrowInt)
234 EVT_BUTTON(Except_ThrowObject, MyDialog::OnThrowObject)
f78e4942 235 EVT_BUTTON(Except_Crash, MyDialog::OnCrash)
556b8c1a
VZ
236END_EVENT_TABLE()
237
be5a51fb 238// Create a new application object: this macro will allow wxWidgets to create
556b8c1a
VZ
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)
243IMPLEMENT_APP(MyApp)
244
245// ============================================================================
246// MyApp implementation
247// ============================================================================
248
249// 'Main program' equivalent: the program execution "starts" here
250bool MyApp::OnInit()
251{
45e6e6f8
VZ
252 if ( !wxApp::OnInit() )
253 return false;
254
556b8c1a 255 // create the main application window
cc9a3957 256 MyFrame *frame = new MyFrame();
556b8c1a
VZ
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
cc9a3957 268bool MyApp::OnExceptionInMainLoop()
556b8c1a
VZ
269{
270 try
271 {
cc9a3957 272 throw;
556b8c1a
VZ
273 }
274 catch ( int i )
275 {
9a83f860 276 wxLogWarning(wxT("Caught an int %d in MyApp."), i);
556b8c1a 277 }
cc9a3957
VZ
278 catch ( MyException& e )
279 {
9a83f860 280 wxLogWarning(wxT("Caught MyException(%s) in MyApp."), e.what());
cc9a3957
VZ
281 }
282 catch ( ... )
283 {
284 throw;
285 }
286
287 return true;
556b8c1a
VZ
288}
289
290void MyApp::OnUnhandledException()
291{
cc9a3957
VZ
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 {
9a83f860
VZ
303 wxMessageBox(wxT("Unhandled exception caught, program will terminate."),
304 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
cc9a3957
VZ
305 }
306}
307
308void MyApp::OnFatalException()
309{
9a83f860
VZ
310 wxMessageBox(wxT("Program has crashed and will terminate."),
311 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
556b8c1a
VZ
312}
313
5cd3213b
VZ
314void MyApp::OnAssertFailure(const wxChar *file,
315 int line,
316 const wxChar *func,
317 const wxChar *cond,
318 const wxChar *msg)
3eeb7e10 319{
2d8e0096
VZ
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 )
5cd3213b
VZ
331 {
332 wxApp::OnAssertFailure(file, line, func, cond, msg);
333 }
3eeb7e10
VZ
334}
335
556b8c1a
VZ
336// ============================================================================
337// MyFrame implementation
338// ============================================================================
339
340// frame constructor
cc9a3957 341MyFrame::MyFrame()
9a83f860 342 : wxFrame(NULL, wxID_ANY, wxT("Except wxWidgets App"),
cc9a3957 343 wxPoint(50, 50), wxSize(450, 340))
556b8c1a
VZ
344{
345 // set the frame icon
d32b901b 346 SetIcon(wxICON(sample));
556b8c1a
VZ
347
348#if wxUSE_MENUS
349 // create a menu bar
350 wxMenu *menuFile = new wxMenu;
9a83f860 351 menuFile->Append(Except_Dialog, wxT("Show &dialog\tCtrl-D"));
cc9a3957 352 menuFile->AppendSeparator();
9a83f860
VZ
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"));
cc9a3957 356 menuFile->Append(Except_ThrowUnhandled,
9a83f860
VZ
357 wxT("Throw &unhandled exception\tCtrl-U"));
358 menuFile->Append(Except_Crash, wxT("&Crash\tCtrl-C"));
55fd62c1
VZ
359 menuFile->Append(Except_Trap, "&Trap\tCtrl-T",
360 "Break into the debugger (if one is running)");
cc9a3957 361 menuFile->AppendSeparator();
b6b375a9 362#if wxUSE_ON_FATAL_EXCEPTION
9a83f860 363 menuFile->AppendCheckItem(Except_HandleCrash, wxT("&Handle crashes\tCtrl-H"));
556b8c1a 364 menuFile->AppendSeparator();
3eeb7e10 365#endif // wxUSE_ON_FATAL_EXCEPTION
9a83f860 366 menuFile->Append(Except_ShowAssert, wxT("Provoke &assert failure\tCtrl-A"));
2d8e0096
VZ
367#if wxUSE_THREADS
368 menuFile->Append(Except_ShowAssertInThread,
369 wxT("Assert failure in &thread\tShift-Ctrl-A"));
370#endif // wxUSE_THREADS
3eeb7e10 371 menuFile->AppendSeparator();
9a83f860 372 menuFile->Append(Except_Quit, wxT("E&xit\tCtrl-Q"), wxT("Quit this program"));
556b8c1a
VZ
373
374 wxMenu *helpMenu = new wxMenu;
2d143b66 375 helpMenu->Append(Except_About, wxT("&About\tF1"), wxT("Show about dialog"));
556b8c1a
VZ
376
377 // now append the freshly created menu to the menu bar...
378 wxMenuBar *menuBar = new wxMenuBar();
9a83f860
VZ
379 menuBar->Append(menuFile, wxT("&File"));
380 menuBar->Append(helpMenu, wxT("&Help"));
556b8c1a
VZ
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);
9a83f860 389 SetStatusText(wxT("Welcome to wxWidgets!"));
556b8c1a
VZ
390#endif // wxUSE_STATUSBAR
391}
392
393bool MyFrame::ProcessEvent(wxEvent& event)
394{
395 try
396 {
397 return wxFrame::ProcessEvent(event);
398 }
399 catch ( const wxChar *msg )
400 {
9a83f860 401 wxLogMessage(wxT("Caught a string \"%s\" in MyFrame"), msg);
556b8c1a
VZ
402
403 return true;
404 }
405}
406
407void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
408{
409 // true is to force the frame to close
410 Close(true);
411}
412
413void MyFrame::OnDialog(wxCommandEvent& WXUNUSED(event))
414{
df5a063f
VZ
415 try
416 {
417 MyDialog dlg(this);
556b8c1a 418
df5a063f
VZ
419 dlg.ShowModal();
420 }
421 catch ( ... )
422 {
9a83f860 423 wxLogWarning(wxT("An exception in MyDialog"));
cc9a3957 424
df5a063f
VZ
425 Destroy();
426 throw;
427 }
556b8c1a
VZ
428}
429
cc9a3957
VZ
430void MyFrame::OnThrowInt(wxCommandEvent& WXUNUSED(event))
431{
432 throw -17;
433}
434
556b8c1a
VZ
435void MyFrame::OnThrowString(wxCommandEvent& WXUNUSED(event))
436{
9a83f860 437 throw wxT("string thrown from MyFrame");
cc9a3957
VZ
438}
439
440void MyFrame::OnThrowObject(wxCommandEvent& WXUNUSED(event))
441{
9a83f860 442 throw MyException(wxT("Exception thrown from MyFrame"));
cc9a3957
VZ
443}
444
445void MyFrame::OnThrowUnhandled(wxCommandEvent& WXUNUSED(event))
446{
447 throw UnhandledException();
448}
449
450void MyFrame::OnCrash(wxCommandEvent& WXUNUSED(event))
451{
452 DoCrash();
453}
454
55fd62c1
VZ
455void MyFrame::OnTrap(wxCommandEvent& WXUNUSED(event))
456{
457 wxTrap();
458}
459
b6b375a9
WS
460#if wxUSE_ON_FATAL_EXCEPTION
461
cc9a3957
VZ
462void MyFrame::OnHandleCrash(wxCommandEvent& event)
463{
464 wxHandleFatalExceptions(event.IsChecked());
556b8c1a
VZ
465}
466
3eeb7e10
VZ
467#endif // wxUSE_ON_FATAL_EXCEPTION
468
3eeb7e10
VZ
469void MyFrame::OnShowAssert(wxCommandEvent& WXUNUSED(event))
470{
471 // provoke an assert from wxArrayString
472 wxArrayString arr;
473 arr[0];
474}
475
2d8e0096
VZ
476#if wxUSE_THREADS
477
478void 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
556b8c1a
VZ
505void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
506{
507 wxString msg;
9a83f860
VZ
508 msg.Printf( wxT("This is the About dialog of the except sample.\n")
509 wxT("Welcome to %s"), wxVERSION_STRING);
556b8c1a 510
9a83f860 511 wxMessageBox(msg, wxT("About Except"), wxOK | wxICON_INFORMATION, this);
556b8c1a
VZ
512}
513
514// ============================================================================
515// MyDialog implementation
516// ============================================================================
517
518MyDialog::MyDialog(wxFrame *parent)
9a83f860 519 : wxDialog(parent, wxID_ANY, wxString(wxT("Throw exception dialog")))
556b8c1a
VZ
520{
521 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
522
9a83f860 523 sizerTop->Add(new wxButton(this, Except_ThrowInt, wxT("Throw &int")),
556b8c1a 524 0, wxCENTRE | wxALL, 5);
9a83f860 525 sizerTop->Add(new wxButton(this, Except_ThrowObject, wxT("Throw &object")),
556b8c1a 526 0, wxCENTRE | wxALL, 5);
9a83f860 527 sizerTop->Add(new wxButton(this, Except_Crash, wxT("&Crash")),
f78e4942 528 0, wxCENTRE | wxALL, 5);
9a83f860 529 sizerTop->Add(new wxButton(this, wxID_CANCEL, wxT("&Cancel")),
556b8c1a
VZ
530 0, wxCENTRE | wxALL, 5);
531
92c01615 532 SetSizerAndFit(sizerTop);
556b8c1a
VZ
533}
534
535void MyDialog::OnThrowInt(wxCommandEvent& WXUNUSED(event))
536{
537 throw 17;
538}
539
540void MyDialog::OnThrowObject(wxCommandEvent& WXUNUSED(event))
541{
9a83f860 542 throw MyException(wxT("Exception thrown from MyDialog"));
556b8c1a
VZ
543}
544
f78e4942
VZ
545void MyDialog::OnCrash(wxCommandEvent& WXUNUSED(event))
546{
cc9a3957 547 DoCrash();
f78e4942
VZ
548}
549