Convert wxFSW_EVENT_{WARNING,ERROR} to string correctly.
[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 #if wxUSE_ON_FATAL_EXCEPTION
124 void OnHandleCrash(wxCommandEvent& event);
125 #endif
126
127 protected:
128
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
133 // provoke assert in main or worker thread
134 //
135 // this is used to show how an assert failure message box looks like
136 void OnShowAssert(wxCommandEvent& event);
137 #if wxUSE_THREADS
138 void OnShowAssertInThread(wxCommandEvent& event);
139 #endif // wxUSE_THREADS
140
141 private:
142 // any class wishing to process wxWidgets events must use this macro
143 DECLARE_EVENT_TABLE()
144 };
145
146 // A simple dialog which has only some buttons to throw exceptions
147 class MyDialog : public wxDialog
148 {
149 public:
150 MyDialog(wxFrame *parent);
151
152 // event handlers
153 void OnThrowInt(wxCommandEvent& event);
154 void OnThrowObject(wxCommandEvent& event);
155 void OnCrash(wxCommandEvent& event);
156
157 private:
158 DECLARE_EVENT_TABLE()
159 };
160
161 // A trivial exception class
162 class MyException
163 {
164 public:
165 MyException(const wxString& msg) : m_msg(msg) { }
166
167 const wxChar *what() const { return m_msg.c_str(); }
168
169 private:
170 wxString m_msg;
171 };
172
173 // Another exception class which just has to be different from anything else
174 class UnhandledException
175 {
176 };
177
178 // ----------------------------------------------------------------------------
179 // constants
180 // ----------------------------------------------------------------------------
181
182 // IDs for the controls and the menu commands
183 enum
184 {
185 // control ids and menu items
186 Except_ThrowInt = wxID_HIGHEST,
187 Except_ThrowString,
188 Except_ThrowObject,
189 Except_ThrowUnhandled,
190 Except_Crash,
191 #if wxUSE_ON_FATAL_EXCEPTION
192 Except_HandleCrash,
193 #endif // wxUSE_ON_FATAL_EXCEPTION
194 Except_ShowAssert,
195 #if wxUSE_THREADS
196 Except_ShowAssertInThread,
197 #endif // wxUSE_THREADS
198 Except_Dialog,
199
200 Except_Quit = wxID_EXIT,
201 Except_About = wxID_ABOUT
202 };
203
204 // ----------------------------------------------------------------------------
205 // event tables and other macros for wxWidgets
206 // ----------------------------------------------------------------------------
207
208 // the event tables connect the wxWidgets events with the functions (event
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.
211 BEGIN_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)
215 EVT_MENU(Except_ThrowInt, MyFrame::OnThrowInt)
216 EVT_MENU(Except_ThrowString, MyFrame::OnThrowString)
217 EVT_MENU(Except_ThrowObject, MyFrame::OnThrowObject)
218 EVT_MENU(Except_ThrowUnhandled, MyFrame::OnThrowUnhandled)
219 EVT_MENU(Except_Crash, MyFrame::OnCrash)
220 #if wxUSE_ON_FATAL_EXCEPTION
221 EVT_MENU(Except_HandleCrash, MyFrame::OnHandleCrash)
222 #endif // wxUSE_ON_FATAL_EXCEPTION
223 EVT_MENU(Except_ShowAssert, MyFrame::OnShowAssert)
224 #if wxUSE_THREADS
225 EVT_MENU(Except_ShowAssertInThread, MyFrame::OnShowAssertInThread)
226 #endif // wxUSE_THREADS
227 END_EVENT_TABLE()
228
229 BEGIN_EVENT_TABLE(MyDialog, wxDialog)
230 EVT_BUTTON(Except_ThrowInt, MyDialog::OnThrowInt)
231 EVT_BUTTON(Except_ThrowObject, MyDialog::OnThrowObject)
232 EVT_BUTTON(Except_Crash, MyDialog::OnCrash)
233 END_EVENT_TABLE()
234
235 // Create a new application object: this macro will allow wxWidgets to create
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)
240 IMPLEMENT_APP(MyApp)
241
242 // ============================================================================
243 // MyApp implementation
244 // ============================================================================
245
246 // 'Main program' equivalent: the program execution "starts" here
247 bool MyApp::OnInit()
248 {
249 if ( !wxApp::OnInit() )
250 return false;
251
252 // create the main application window
253 MyFrame *frame = new MyFrame();
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
265 bool MyApp::OnExceptionInMainLoop()
266 {
267 try
268 {
269 throw;
270 }
271 catch ( int i )
272 {
273 wxLogWarning(wxT("Caught an int %d in MyApp."), i);
274 }
275 catch ( MyException& e )
276 {
277 wxLogWarning(wxT("Caught MyException(%s) in MyApp."), e.what());
278 }
279 catch ( ... )
280 {
281 throw;
282 }
283
284 return true;
285 }
286
287 void MyApp::OnUnhandledException()
288 {
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 {
300 wxMessageBox(wxT("Unhandled exception caught, program will terminate."),
301 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
302 }
303 }
304
305 void MyApp::OnFatalException()
306 {
307 wxMessageBox(wxT("Program has crashed and will terminate."),
308 wxT("wxExcept Sample"), wxOK | wxICON_ERROR);
309 }
310
311 void MyApp::OnAssertFailure(const wxChar *file,
312 int line,
313 const wxChar *func,
314 const wxChar *cond,
315 const wxChar *msg)
316 {
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 )
328 {
329 wxApp::OnAssertFailure(file, line, func, cond, msg);
330 }
331 }
332
333 // ============================================================================
334 // MyFrame implementation
335 // ============================================================================
336
337 // frame constructor
338 MyFrame::MyFrame()
339 : wxFrame(NULL, wxID_ANY, wxT("Except wxWidgets App"),
340 wxPoint(50, 50), wxSize(450, 340))
341 {
342 // set the frame icon
343 SetIcon(wxICON(sample));
344
345 #if wxUSE_MENUS
346 // create a menu bar
347 wxMenu *menuFile = new wxMenu;
348 menuFile->Append(Except_Dialog, wxT("Show &dialog\tCtrl-D"));
349 menuFile->AppendSeparator();
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"));
353 menuFile->Append(Except_ThrowUnhandled,
354 wxT("Throw &unhandled exception\tCtrl-U"));
355 menuFile->Append(Except_Crash, wxT("&Crash\tCtrl-C"));
356 menuFile->AppendSeparator();
357 #if wxUSE_ON_FATAL_EXCEPTION
358 menuFile->AppendCheckItem(Except_HandleCrash, wxT("&Handle crashes\tCtrl-H"));
359 menuFile->AppendSeparator();
360 #endif // wxUSE_ON_FATAL_EXCEPTION
361 menuFile->Append(Except_ShowAssert, wxT("Provoke &assert failure\tCtrl-A"));
362 #if wxUSE_THREADS
363 menuFile->Append(Except_ShowAssertInThread,
364 wxT("Assert failure in &thread\tShift-Ctrl-A"));
365 #endif // wxUSE_THREADS
366 menuFile->AppendSeparator();
367 menuFile->Append(Except_Quit, wxT("E&xit\tCtrl-Q"), wxT("Quit this program"));
368
369 wxMenu *helpMenu = new wxMenu;
370 helpMenu->Append(Except_About, wxT("&About\tF1"), wxT("Show about dialog"));
371
372 // now append the freshly created menu to the menu bar...
373 wxMenuBar *menuBar = new wxMenuBar();
374 menuBar->Append(menuFile, wxT("&File"));
375 menuBar->Append(helpMenu, wxT("&Help"));
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);
384 SetStatusText(wxT("Welcome to wxWidgets!"));
385 #endif // wxUSE_STATUSBAR
386 }
387
388 bool MyFrame::ProcessEvent(wxEvent& event)
389 {
390 try
391 {
392 return wxFrame::ProcessEvent(event);
393 }
394 catch ( const wxChar *msg )
395 {
396 wxLogMessage(wxT("Caught a string \"%s\" in MyFrame"), msg);
397
398 return true;
399 }
400 }
401
402 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
403 {
404 // true is to force the frame to close
405 Close(true);
406 }
407
408 void MyFrame::OnDialog(wxCommandEvent& WXUNUSED(event))
409 {
410 try
411 {
412 MyDialog dlg(this);
413
414 dlg.ShowModal();
415 }
416 catch ( ... )
417 {
418 wxLogWarning(wxT("An exception in MyDialog"));
419
420 Destroy();
421 throw;
422 }
423 }
424
425 void MyFrame::OnThrowInt(wxCommandEvent& WXUNUSED(event))
426 {
427 throw -17;
428 }
429
430 void MyFrame::OnThrowString(wxCommandEvent& WXUNUSED(event))
431 {
432 throw wxT("string thrown from MyFrame");
433 }
434
435 void MyFrame::OnThrowObject(wxCommandEvent& WXUNUSED(event))
436 {
437 throw MyException(wxT("Exception thrown from MyFrame"));
438 }
439
440 void MyFrame::OnThrowUnhandled(wxCommandEvent& WXUNUSED(event))
441 {
442 throw UnhandledException();
443 }
444
445 void MyFrame::OnCrash(wxCommandEvent& WXUNUSED(event))
446 {
447 DoCrash();
448 }
449
450 #if wxUSE_ON_FATAL_EXCEPTION
451
452 void MyFrame::OnHandleCrash(wxCommandEvent& event)
453 {
454 wxHandleFatalExceptions(event.IsChecked());
455 }
456
457 #endif // wxUSE_ON_FATAL_EXCEPTION
458
459 void MyFrame::OnShowAssert(wxCommandEvent& WXUNUSED(event))
460 {
461 // provoke an assert from wxArrayString
462 wxArrayString arr;
463 arr[0];
464 }
465
466 #if wxUSE_THREADS
467
468 void 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
495 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
496 {
497 wxString msg;
498 msg.Printf( wxT("This is the About dialog of the except sample.\n")
499 wxT("Welcome to %s"), wxVERSION_STRING);
500
501 wxMessageBox(msg, wxT("About Except"), wxOK | wxICON_INFORMATION, this);
502 }
503
504 // ============================================================================
505 // MyDialog implementation
506 // ============================================================================
507
508 MyDialog::MyDialog(wxFrame *parent)
509 : wxDialog(parent, wxID_ANY, wxString(wxT("Throw exception dialog")))
510 {
511 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
512
513 sizerTop->Add(new wxButton(this, Except_ThrowInt, wxT("Throw &int")),
514 0, wxCENTRE | wxALL, 5);
515 sizerTop->Add(new wxButton(this, Except_ThrowObject, wxT("Throw &object")),
516 0, wxCENTRE | wxALL, 5);
517 sizerTop->Add(new wxButton(this, Except_Crash, wxT("&Crash")),
518 0, wxCENTRE | wxALL, 5);
519 sizerTop->Add(new wxButton(this, wxID_CANCEL, wxT("&Cancel")),
520 0, wxCENTRE | wxALL, 5);
521
522 SetSizerAndFit(sizerTop);
523 }
524
525 void MyDialog::OnThrowInt(wxCommandEvent& WXUNUSED(event))
526 {
527 throw 17;
528 }
529
530 void MyDialog::OnThrowObject(wxCommandEvent& WXUNUSED(event))
531 {
532 throw MyException(wxT("Exception thrown from MyDialog"));
533 }
534
535 void MyDialog::OnCrash(wxCommandEvent& WXUNUSED(event))
536 {
537 DoCrash();
538 }
539