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