1 /////////////////////////////////////////////////////////////////////////////
2 // Name: samples/except/except.cpp
3 // Purpose: shows how C++ exceptions can be used in wxWidgets
4 // Author: Vadim Zeitlin
8 // Copyright: (c) 2003-2005 Vadim Zeitlin
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ============================================================================
14 // ============================================================================
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
28 #error "This sample only works with wxUSE_EXCEPTIONS == 1"
29 #endif // !wxUSE_EXCEPTIONS
31 // for all others, include the necessary headers (this file is usually all you
32 // need because it includes almost all "standard" wxWidgets headers)
38 #include "wx/dialog.h"
41 #include "wx/button.h"
45 #include "wx/msgdlg.h"
48 #include "wx/thread.h"
51 // ----------------------------------------------------------------------------
53 // ----------------------------------------------------------------------------
55 // the application icon (under Windows and OS/2 it is in resources)
56 #ifndef wxHAS_IMAGES_IN_RESOURCES
57 #include "../sample.xpm"
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
67 strcpy(p
, "Let's crash");
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
74 // Define a new application type, each program should derive a class from wxApp
75 class MyApp
: public wxApp
78 // override base class virtuals
79 // ----------------------------
82 virtual bool OnInit();
84 // 2nd-level exception handling: we get all the exceptions occurring in any
86 virtual bool OnExceptionInMainLoop();
88 // 3rd, and final, level exception handling: whenever an unhandled
89 // exception is caught, this function is called
90 virtual void OnUnhandledException();
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();
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
,
105 // Define a new frame type: this is going to be our main frame
106 class MyFrame
: public wxFrame
112 // event handlers (these functions should _not_ be virtual)
113 void OnQuit(wxCommandEvent
& event
);
114 void OnAbout(wxCommandEvent
& event
);
115 void OnDialog(wxCommandEvent
& event
);
117 void OnThrowInt(wxCommandEvent
& event
);
118 void OnThrowString(wxCommandEvent
& event
);
119 void OnThrowObject(wxCommandEvent
& event
);
120 void OnThrowUnhandled(wxCommandEvent
& event
);
122 void OnCrash(wxCommandEvent
& event
);
123 void OnTrap(wxCommandEvent
& event
);
124 #if wxUSE_ON_FATAL_EXCEPTION
125 void OnHandleCrash(wxCommandEvent
& event
);
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
);
134 // provoke assert in main or worker thread
136 // this is used to show how an assert failure message box looks like
137 void OnShowAssert(wxCommandEvent
& event
);
139 void OnShowAssertInThread(wxCommandEvent
& event
);
140 #endif // wxUSE_THREADS
143 // any class wishing to process wxWidgets events must use this macro
144 DECLARE_EVENT_TABLE()
147 // A simple dialog which has only some buttons to throw exceptions
148 class MyDialog
: public wxDialog
151 MyDialog(wxFrame
*parent
);
154 void OnThrowInt(wxCommandEvent
& event
);
155 void OnThrowObject(wxCommandEvent
& event
);
156 void OnCrash(wxCommandEvent
& event
);
159 DECLARE_EVENT_TABLE()
162 // A trivial exception class
166 MyException(const wxString
& msg
) : m_msg(msg
) { }
168 const wxChar
*what() const { return m_msg
.c_str(); }
174 // Another exception class which just has to be different from anything else
175 class UnhandledException
179 // ----------------------------------------------------------------------------
181 // ----------------------------------------------------------------------------
183 // IDs for the controls and the menu commands
186 // control ids and menu items
187 Except_ThrowInt
= wxID_HIGHEST
,
190 Except_ThrowUnhandled
,
193 #if wxUSE_ON_FATAL_EXCEPTION
195 #endif // wxUSE_ON_FATAL_EXCEPTION
198 Except_ShowAssertInThread
,
199 #endif // wxUSE_THREADS
202 Except_Quit
= wxID_EXIT
,
203 Except_About
= wxID_ABOUT
206 // ----------------------------------------------------------------------------
207 // event tables and other macros for wxWidgets
208 // ----------------------------------------------------------------------------
210 // the event tables connect the wxWidgets events with the functions (event
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.
213 BEGIN_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
)
217 EVT_MENU(Except_ThrowInt
, MyFrame::OnThrowInt
)
218 EVT_MENU(Except_ThrowString
, MyFrame::OnThrowString
)
219 EVT_MENU(Except_ThrowObject
, MyFrame::OnThrowObject
)
220 EVT_MENU(Except_ThrowUnhandled
, MyFrame::OnThrowUnhandled
)
221 EVT_MENU(Except_Crash
, MyFrame::OnCrash
)
222 EVT_MENU(Except_Trap
, MyFrame::OnTrap
)
223 #if wxUSE_ON_FATAL_EXCEPTION
224 EVT_MENU(Except_HandleCrash
, MyFrame::OnHandleCrash
)
225 #endif // wxUSE_ON_FATAL_EXCEPTION
226 EVT_MENU(Except_ShowAssert
, MyFrame::OnShowAssert
)
228 EVT_MENU(Except_ShowAssertInThread
, MyFrame::OnShowAssertInThread
)
229 #endif // wxUSE_THREADS
232 BEGIN_EVENT_TABLE(MyDialog
, wxDialog
)
233 EVT_BUTTON(Except_ThrowInt
, MyDialog::OnThrowInt
)
234 EVT_BUTTON(Except_ThrowObject
, MyDialog::OnThrowObject
)
235 EVT_BUTTON(Except_Crash
, MyDialog::OnCrash
)
238 // Create a new application object: this macro will allow wxWidgets to create
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
245 // ============================================================================
246 // MyApp implementation
247 // ============================================================================
249 // 'Main program' equivalent: the program execution "starts" here
252 if ( !wxApp::OnInit() )
255 // create the main application window
256 MyFrame
*frame
= new MyFrame();
258 // and show it (the frames, unlike simple controls, are not shown when
259 // created initially)
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.
268 bool MyApp::OnExceptionInMainLoop()
276 wxLogWarning(wxT("Caught an int %d in MyApp."), i
);
278 catch ( MyException
& e
)
280 wxLogWarning(wxT("Caught MyException(%s) in MyApp."), e
.what());
290 void MyApp::OnUnhandledException()
292 // this shows how we may let some exception propagate uncaught
297 catch ( UnhandledException
& )
303 wxMessageBox(wxT("Unhandled exception caught, program will terminate."),
304 wxT("wxExcept Sample"), wxOK
| wxICON_ERROR
);
308 void MyApp::OnFatalException()
310 wxMessageBox(wxT("Program has crashed and will terminate."),
311 wxT("wxExcept Sample"), wxOK
| wxICON_ERROR
);
314 void MyApp::OnAssertFailure(const wxChar
*file
,
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() ||
325 wxString::Format("An assert failed in %s().", func
) +
327 "Do you want to call the default assert handler?",
329 wxYES_NO
| wxICON_QUESTION
332 wxApp::OnAssertFailure(file
, line
, func
, cond
, msg
);
336 // ============================================================================
337 // MyFrame implementation
338 // ============================================================================
342 : wxFrame(NULL
, wxID_ANY
, wxT("Except wxWidgets App"),
343 wxPoint(50, 50), wxSize(450, 340))
345 // set the frame icon
346 SetIcon(wxICON(sample
));
350 wxMenu
*menuFile
= new wxMenu
;
351 menuFile
->Append(Except_Dialog
, wxT("Show &dialog\tCtrl-D"));
352 menuFile
->AppendSeparator();
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"));
356 menuFile
->Append(Except_ThrowUnhandled
,
357 wxT("Throw &unhandled exception\tCtrl-U"));
358 menuFile
->Append(Except_Crash
, wxT("&Crash\tCtrl-C"));
359 menuFile
->Append(Except_Trap
, "&Trap\tCtrl-T",
360 "Break into the debugger (if one is running)");
361 menuFile
->AppendSeparator();
362 #if wxUSE_ON_FATAL_EXCEPTION
363 menuFile
->AppendCheckItem(Except_HandleCrash
, wxT("&Handle crashes\tCtrl-H"));
364 menuFile
->AppendSeparator();
365 #endif // wxUSE_ON_FATAL_EXCEPTION
366 menuFile
->Append(Except_ShowAssert
, wxT("Provoke &assert failure\tCtrl-A"));
368 menuFile
->Append(Except_ShowAssertInThread
,
369 wxT("Assert failure in &thread\tShift-Ctrl-A"));
370 #endif // wxUSE_THREADS
371 menuFile
->AppendSeparator();
372 menuFile
->Append(Except_Quit
, wxT("E&xit\tCtrl-Q"), wxT("Quit this program"));
374 wxMenu
*helpMenu
= new wxMenu
;
375 helpMenu
->Append(Except_About
, wxT("&About\tF1"), wxT("Show about dialog"));
377 // now append the freshly created menu to the menu bar...
378 wxMenuBar
*menuBar
= new wxMenuBar();
379 menuBar
->Append(menuFile
, wxT("&File"));
380 menuBar
->Append(helpMenu
, wxT("&Help"));
382 // ... and attach this menu bar to the frame
384 #endif // wxUSE_MENUS
386 #if wxUSE_STATUSBAR && !defined(__WXWINCE__)
387 // create a status bar just for fun (by default with 1 pane only)
389 SetStatusText(wxT("Welcome to wxWidgets!"));
390 #endif // wxUSE_STATUSBAR
393 bool MyFrame::ProcessEvent(wxEvent
& event
)
397 return wxFrame::ProcessEvent(event
);
399 catch ( const wxChar
*msg
)
401 wxLogMessage(wxT("Caught a string \"%s\" in MyFrame"), msg
);
407 void MyFrame::OnQuit(wxCommandEvent
& WXUNUSED(event
))
409 // true is to force the frame to close
413 void MyFrame::OnDialog(wxCommandEvent
& WXUNUSED(event
))
423 wxLogWarning(wxT("An exception in MyDialog"));
430 void MyFrame::OnThrowInt(wxCommandEvent
& WXUNUSED(event
))
435 void MyFrame::OnThrowString(wxCommandEvent
& WXUNUSED(event
))
437 throw wxT("string thrown from MyFrame");
440 void MyFrame::OnThrowObject(wxCommandEvent
& WXUNUSED(event
))
442 throw MyException(wxT("Exception thrown from MyFrame"));
445 void MyFrame::OnThrowUnhandled(wxCommandEvent
& WXUNUSED(event
))
447 throw UnhandledException();
450 void MyFrame::OnCrash(wxCommandEvent
& WXUNUSED(event
))
455 void MyFrame::OnTrap(wxCommandEvent
& WXUNUSED(event
))
460 #if wxUSE_ON_FATAL_EXCEPTION
462 void MyFrame::OnHandleCrash(wxCommandEvent
& event
)
464 wxHandleFatalExceptions(event
.IsChecked());
467 #endif // wxUSE_ON_FATAL_EXCEPTION
469 void MyFrame::OnShowAssert(wxCommandEvent
& WXUNUSED(event
))
471 // provoke an assert from wxArrayString
478 void MyFrame::OnShowAssertInThread(wxCommandEvent
& WXUNUSED(event
))
480 class AssertThread
: public wxThread
484 : wxThread(wxTHREAD_JOINABLE
)
489 virtual void *Entry()
491 wxFAIL_MSG("Test assert in another thread.");
503 #endif // wxUSE_THREADS
505 void MyFrame::OnAbout(wxCommandEvent
& WXUNUSED(event
))
508 msg
.Printf( wxT("This is the About dialog of the except sample.\n")
509 wxT("Welcome to %s"), wxVERSION_STRING
);
511 wxMessageBox(msg
, wxT("About Except"), wxOK
| wxICON_INFORMATION
, this);
514 // ============================================================================
515 // MyDialog implementation
516 // ============================================================================
518 MyDialog::MyDialog(wxFrame
*parent
)
519 : wxDialog(parent
, wxID_ANY
, wxString(wxT("Throw exception dialog")))
521 wxSizer
*sizerTop
= new wxBoxSizer(wxVERTICAL
);
523 sizerTop
->Add(new wxButton(this, Except_ThrowInt
, wxT("Throw &int")),
524 0, wxCENTRE
| wxALL
, 5);
525 sizerTop
->Add(new wxButton(this, Except_ThrowObject
, wxT("Throw &object")),
526 0, wxCENTRE
| wxALL
, 5);
527 sizerTop
->Add(new wxButton(this, Except_Crash
, wxT("&Crash")),
528 0, wxCENTRE
| wxALL
, 5);
529 sizerTop
->Add(new wxButton(this, wxID_CANCEL
, wxT("&Cancel")),
530 0, wxCENTRE
| wxALL
, 5);
532 SetSizerAndFit(sizerTop
);
535 void MyDialog::OnThrowInt(wxCommandEvent
& WXUNUSED(event
))
540 void MyDialog::OnThrowObject(wxCommandEvent
& WXUNUSED(event
))
542 throw MyException(wxT("Exception thrown from MyDialog"));
545 void MyDialog::OnCrash(wxCommandEvent
& WXUNUSED(event
))