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