Cross-Platform GUI Programming with wxWidgets
|
Often a bug will only surface some time after the logic error actually occurs. If an inconsistent or invalid value isn't detected early, the program can execute thousands of lines of code before it crashes or you get mysterious results. You can spend a lot of time trying to figure out the real cause of the error. However, if you add regular checks to your codefor example, to detect bad values passed to functionsyour code will end up being much more robust, and you will save yourself (and your users) a potentially huge amount of trouble. This technique is called defensive programming, and your classes and functions can defend themselves both against improper use by other code and against internal logic errors. Because most of these checks are compiled out in release builds, there is no overhead. As you would expect, wxWidgets does a lot of error checking internally, and you can use the same macros and functions in your own code. There are three main families of macros: variations of wxASSERT, wxFAIL, and wxCHECK. wxASSERT macros show an error message if the argument doesn't evaluate to TRue; the checks only occur in debug builds. wxFAIL will always generate an error message and is equivalent to wxASSERT(false). These checks are also removed in the release build. wxCHECK checks that the condition is TRue and returns a given value if not. Unlike the others, occurrences of wxCHECK remain (but do not display a message) in release builds. These macros have variations that let you display a custom error message in the assertion message box. Here are some examples of using these macros. // Add two positive numbers under 100 int AddPositive(int a, int b) { // Check if a is positive wxASSERT(a > 0); // Check if b is positive, with custom error message wxASSERT_MSG(b > 0, wxT("The second number must be positive!")); int c = a + b; // Return -1 if the result was not positive wxCHECK_MSG(c > 0, -1, wxT("Result must be positive!")); return c; } You can also use wxCHECK2 and wxCHECK2_MSG to execute an arbitrary operation if the check failed instead of just returning a value. wxCHECK_RET can be used in void functions and returns no value. For less frequently used macros, such as wxCOMPILE_TIME_ASSERT and wxASSERT_MIN_BITSIZE, please refer to the reference manual. Figure 15-1 shows the assertion dialog that appears when an assertion condition has evaluated to false. The user can stop the program (Yes), ignore the warning (No), or ignore all further warnings (Cancel). If the program is running under a debugger, stopping the program will cause a break in the debugger, and you can navigate the call stack to see exactly where the problem was and the values of variables at that point. Figure 15-1. Assertion alert
|
|