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