Saving Errors to Logs


Sometimes it is simply not helpful to display error messages to the user. If the error is not critical, it’s more likely to simply confuse your end user without accomplishing anything useful. In fact, it is not prudent to display all messages to the user. One answer to this is to simply log the error messages to a flat file. Later, support personnel can read the log and see what has been occurring and perhaps diagnose what is wrong. You can even combine a message to the user with a log entry if you wish. The following example shows you how to log error messages to a file.

Example 7.4

Step 1: Enter the following code into your favorite text editor.

#include <fstream> #include <iostream> using namespace std;   void logerror(int); int main() {  int answer, divisor, dividend;  try {   cout << "Please enter an integer \n";   cin >>divisor;       cout << "Please enter another integer \n";        cin >> dividend;       if(dividend ==0)      throw 0;           answer = divisor/dividend;      cout << answer;       return 0; } catch (int i) {   cout << "You cannot divide by zero";       logerror(0); } catch (...) {   logerror(1); } } void logerror(int type) { fstream myfile; myfile.open("error.txt",ios::app); if (type==0)        myfile<<"Division by zero error \n"; else       myfile<< "INdeterminate error \n"; return; } 

Step 2: Compile the code.

Step 3: Run the code. You should see something like what is depicted in Figure 7.3.

click to expand
Figure 7.3: Writing errors to a log.

Now, if you open the file called error.txt on your hard drive, you should see something similar to Figure 7.4.

click to expand
Figure 7.4: Viewing an error log.

This code sample has illustrated a number of important things. The first, and most obvious, is that you can log errors to a flat file if you so desire. But what you have also seen in this example is a variety of techniques from the past several chapters brought together. If you view each chapter and lesson as a separate and discrete entity, then you will miss the real point of this book. You should work to combine different techniques so that they work together to create useful applications.




C++ Programming Fundamentals
C++ Programming Fundamentals (Cyberrookies)
ISBN: 1584502371
EAN: 2147483647
Year: 2005
Pages: 197
Authors: Chuck Easttom

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net