Wednesday, September 21, 2011

C++ ERRORS









REVISED: Sunday, March 3, 2013



CONTENTS:
I.       INTRODUCTION TO C++ ERRORS
II.     ASSUMPTIONS
III.    C++ COMPILE-TIME ERRORS
IV.   C++ LINK-TIME ERRORS
V.    C++ RUN-TIME ERRORS
VI.   C++ LOGIC ERRORS
VII.  C++ EXCEPTION ERRORS AND EXCEPTION HANDLING
VIII. C++ EXCEPTION HANDLING  EXAMPLE PROGRAM SOURCE CODE
IX.   HANDLING CATASTROPHIC C++ EVENTS

YOU WILL LEARN:
1. Compile-time errors.
2. Link-time errors.
3. Run-time errors.
4. Logic errors.
5. Exception handling.
6.     Handling Catastrophic Events.

I. INTRODUCTION TO C++ ERRORS

Welcome to the “C++ Errors Tutorial.”

II. ASSUMPTIONS

This tutorial discusses errors.


A Certified Public Accountants (CPA), or Chartered Public Accountant (CPA), depending on what country you are in, audits systems looking for errors and irregularities.

What is an error?

An error is an honest mistake.


A payroll clerk enters an $8,000 bonus payment through the payroll system when it was really supposed to be only $3,000. When someone is working very fast and especially when they are tired, sometimes a 3 looks light an 8 and honest errors are created.

What is an irregularity?


An irregularity is not an honest mistake.

An irregularity is alleged fraud until it’s proven in a court of law to actually be fraud.


At a minimum the systems you design should detect and report non-public accessor method attempts to access private data, these attempts are irregularities.


Public accessor methods should be the only functions other parts of your program call to get and set the private member variables.


A.  As a programmer you are not responsible for:

1. Hardware malfunctions.

2. System software malfunctions.


B.  However, as a programmer you are responsible for:

1. Your Application


For example, designing and writing programs that detect and report errors and irregularities.


Each time your program performs a task; your program should test to see if the task was performed properly. When the test results show the program did not perform the task properly, your program should perform error processing. If user input is involved, the user should be notified to re-input corrected data.

2. Complying Legal Requirements


For example legal requirements of the field in which you are providing your professional programming services.


If you design, program, market, and provide services for a particular industry your clients assume you have professional expertise in that industry and can hold you legally accountable within the limits of the law.

For example, lets look, at a very high level, without taking internal controls into consideration, at the information which has to be considered when designing "sales" and their matching "cash receipts" into a customer requested computer accounting system.

Generally Accepted Accounting Principles (GAAP) are used to evaluate both manual and computer accounting systems.

The customer has requested, at a minimum, at midnight every day, there should be a total company, "General Ledger Trial Balance" report showing: "Assets" equal "Liabilities" plus "Owners Equity;" an "Income Statement;" and a "Balance Sheet."

a.  The customer is requesting daily computer accounting system generated balancing of all "General Ledger Account Subsidiary Ledgers" to their source document computer files.

For example: A sale is made.

The company salesperson retains a copy of the computer generated sales receipt; and receives the cash payment from their customer.

Their customer receives the purchased inventory and the original copy of the computer generated sales receipt from the company salesperson.

The sale is recorded as a credit in a "sales General Ledger Account Subsidiary Ledger file" in the company computer system.    

Cash collected from the customer, is recorded as a debit in a "cash General Ledger Account Subsidiary Ledger file" in the company computer system; and deposited daily at the bank.

The daily balancing is the balancing of  the sales receipts for that day with the computer "sales General Ledger Account Subsidiary Ledger file" entries for that day.  And, the cash receipts for that day with the computer "cash General Ledger Account Subsidiary Ledger file" entries for that day.

b.  The customer is requesting daily computer accounting system generated balancing, of all general ledger account Subsidiary Ledgers, to the "General Ledger Trial Balance."

These must be separate files.

The customer is requesting "sales General Ledger Account Subsidiary Ledger file" and a separate common "General Ledger Trial Balance" account file which will include a sales "General Ledger Trial Balance" account.

The customer is requesting "cash General Ledger Account Subsidiary Ledger file" and on the common "General Ledger Trial Balance" account file will be a cash "General Ledger Trial Balance" account."

c.  The customer is requesting daily computer accounting system generated general ledger account Reconciliation Reports, reconciling each out of balance between the Subsidiary Ledgers, and the "General Ledger Trial Balance."

d.  The customer is requesting each reconciliation list all "Unreconcilable Items," out of balance transactions the computer accounting system can not account for. 

e.  The customer is requesting these reports never be created by "manual work-arounds."  The customer believes when an accounting department has to perform any "manual work-arounds" the computer accounting system is not designed properly and the potential for introducing human errors is increased.  

f.  The customer is requesting that they,  the managers and the accountants should be able to review on their personal computer these daily report balances and reconciliations "on demand," whenever they need them.

g.  The customer, the managers, and the accountants will be taking appropriate corrective actions on each "Unreconcileable Item." 

The purpose of the above is not to design a computer accounting system.  The purpose is to point out the magnitude of the information an accounting system designer and programmer have to consider.

An accounting system is just one example, every system design project will have its own unique information to consider.

3. Error Detection and Processing Techniques


For example including  error detection and processing techniques such as exception handling in the design of your program to notify the user of serious errors and permit your program to either continue running or terminate in an orderly manner.


Testing and fixing programs is a very large percent of every major program’s development cost. Become a proficient tester and fixer and your talents will always be in demand.

• III. COMPILE-TIME ERRORS

A.  Compile Time-Errors


Compile-time errors are errors found by the compiler.


You should become very familiar with both the types of errors reported by your compiler, and the error messages used by your compiler.

Sometimes you can not take the compiler error messages literally. For example, sometimes the compiler error message might be reporting problems a couple of lines above where it says the error is located.

1. Common Syntax Errors:

a. Typing mistakes, also called a typo.


b. Placing code between a try block and its corresponding catch handler or between its catch handlers.

c. String literal not terminated.

d. Character literal not terminated.

e. Block not terminated.

f. Mismatched parentheses.


g. Undeclared name or incorrectly spelled function name.


h. Statements not terminated with semicolon.

2. Fence Post Errors


Fence post errors are frequently caused by people not learning the offset zero counting method for arrays and vectors.

3. Narrowing Errors


Narrowing errors are caused by assigning a value too large to fit in a container.

4. Type Errors


Every functions call must include the right number of arguments, in the right order, and of the right type.

IV. LINK-TIME ERRORS


Link-time errors are errors found by the linker. Translation units are the separate compiled parts of a program. The linker will report an error when a function’s declaration in a translation unit does not match its declaration in all other translation units where it is used. Normally these errors are type mismatches.

V. RUN-TIME ERRORS

A.  Run-Time Errors


Run-time errors are errors you find when you run your program.


Bad input can cause run-time errors. Lots of things can cause bad input:


1. Your pet sets on your keyboard.

2. You spill food or drink on your keyboard.


3. User is not trained to use your application.


4. You were not aware of all of the uses your system would be required to perform, and consequently did not design the system properly.


B.  Detect, Report, and Handle Run-Time Errors


Where should your program detect, report, and handle run-time errors?


1. Locally within the caller, the function calling the function?


Due in part to the extensive use of library functions; detecting errors within the caller is not normally a generally accepted programming practice. Libraries are normally licensed and control over fixing the libraries is normally off site, not local.


The caller should receive error reports from the callee and should take the appropriate action based on those error reports. If the error can be fixed locally it is fixed locally. If the error can not be fixed locally it must be coordinated with the third party vendor who licensed the library or source of the error.


2. Within the callee, the called function?


Detecting errors within the callee is normally a generally accepted programming practice.


If you always strive to make your program bullet proof, the called function should be able to handle literally every possible argument value it receives.


Both detecting and reporting errors should normally be done within the callee. The callee should report the errors to the caller. The callee should also report the errors to client management to ensure the errors will not be ignored. If the callee is licensed from a third party vendor, as in the case of some library functions, the callee function should send an error report to the third party vendor via the Internet. The off site third party vendor should fix the error and send a corrected library to the client, normally through an internet update.

VI. LOGIC ERRORS


Logic errors are errors you find when you are reviewing the results of your program, when it does what you told it to do, instead of what you wanted it to do.


VII. EXCEPTION ERRORS AND EXCEPTION HANDLING

A. Exception Errors


Exceptions are near catastrophic events that might happen but are not expected to happen. For example, the new operator will throw an exception if the memory you request can not be allocated.

B. Exception Handling


The following example program is an example of exception handling.

VIII. C++ EXCEPTION HANDLING  EXAMPLE PROGRAM SOURCE CODE

//**********************************
//C++ Errors Tutorial
//Exception Handling
//Divide by zero example:
//**********************************
#ifndef CALC_ERROR_H
#define CALC_ERROR_H
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;
#endif  //CALC_ERROR_H

class Exception
{
    public:

        char message[100];
        int test;

             Exception();

             Exception(char *m, int t);

        void ClearScreen();             
//Clears the screen.

        int  Menu();                       
//Menu.

        void Pause();                     
//Waits for user response.

             ~Exception();

};

//**********************************
//Constructor.
//**********************************
Exception::Exception()
{
    *message = 0;

    test = 0;
}

//**********************************
//Constructor.
//**********************************
Exception::Exception(char *m, int t)
{
    strcpy_s(message, m);

    test = t;
}

//**********************************
//Clear Screen.
//**********************************
void Exception::ClearScreen()
{
    system( "CLS" );

    cout << endl << endl << endl;
}

//**********************************
//  Pause.
//**********************************
void Exception::Pause()
{
    cout << endl << endl << endl;

    cout << "  ";

    system( "PAUSE" );

    cout << endl << endl << endl;
}

//**********************************
//  Menu.
//**********************************
int Exception::Menu()
{
    int choice = 0;

    ClearScreen();

    cout << endl << endl << endl;

    cout << "                     C++ ERRORS TUTORIAL"  << endl;

    cout << "  -------------------------------------------------------------" << endl << endl << endl;

    cout << "  To run the C++ Errors Tutorial" << endl << endl;

    cout << "  type any non zero integer and press return  ==>  ";

    while(!(cin >> choice))
    {
        cin.clear();                    
//resets any fail state

        cin.ignore(256,'\n');           
//discards bad input

        cout << "  Bad Input - Try again" << endl;

    }
    return choice;
}

//**********************************
//Destructor.
//**********************************
Exception::~Exception()
{

}

//**********************************
//MAIN() FUNCTION.
//**********************************
int main(int argc, char* argv[])
{
    int choice  = 0;

    int test = 0;

    Exception time;
       
        choice = time.Menu();

        try
        {
            time.ClearScreen();

            cout << "  Inside try block.";

            time.Pause();

            time.ClearScreen();

            cout << "  If you want an exception, " << endl;

            cout << "  enter any number from 0 to 8 ";

            cout << "and then press return. " << endl << endl;

            cout << "  If you do not want an exception, " << endl;

            cout << "  enter the number 9 ";

            cout << "and then press return ==> ";

            while(!(cin >> test))
            {
                cin.clear();                    
//resets any fail state

                cin.ignore(256,'\n');           //discards bad input

                cout << "  Bad Input - Try again" << endl;

            }

            if ((test>=0) && (test<=8))
            {
                time.ClearScreen();

                throw Exception("  You entered", test);

            }
        }
        catch (Exception t)
        {
            t.ClearScreen();

            cout << "  Exception caught, inside catch block." << endl << endl;

            cout << t.message << " number ";

            cout << t.test << endl;

        }
                catch (...)
        {
            cout << "  Generic exception caught, inside catch block." << endl << endl;

        }
               
    time.Pause();

    return EXIT_SUCCESS;

}

//**********************************


• IX.  HANDLING CATASTROPHIC EVENTS


Exception handling is not intended for run of the mill errors that can be detected by data checking and validating. Exception handling is intended for handling catastrophic events.


Exception handling is an orderly way of handling exceptions which occur during program execution from catastrophic but predictable problems. Exception handling includes error detection, error reporting and error fixing.


C++ uses try blocks for exception handling. A try block starts with the keyword try, followed by braces {} enclosing the code that might create or throw an exception. When an exception occurs within the try block it is thrown as an object.


The operand following the throw keyword of a throw statement determines a type for the thrown exception object. Once the exception object is thrown the try block is terminated and execution passes to the appropriate catch handler.


The exception object is caught using catch, arg receives its value, and the exception object is processed. Catch handlers, also called exception handlers, process the exceptions. At least one catch handler must immediately follow each try block. A catch handler begins with the keyword catch and within parentheses states an exception parameter representing the type of exception the catch handler can process. Any type of object can be thrown as an exception. The body of the catch handler is enclosed by braces {}.

A catch handler can do any or all of the following: report the error to the user, log the error to a file, and terminate the program in an orderly fashion. In the event the program is not terminated control continues to the statement following the last catch handler, following the try block.


The compiler regards the try block and the catch block as a single unit.


When an error does not occur within a try block, control continues to the statement following the last catch handler, following the try block.


The program terminates if an exception is thrown that is not caught by an exception handler.

YOU HAVE LEARNED:
1. Compile-time errors.
2. Link-time errors.
3. Run-time errors.
4. Logic errors.
5. Exception handling.
6. Handling Catastrophic Events.


Elcric Otto Circle




-->

-->

-->







How to Link to My Home Page

It will appear on your website as:
"Link to ELCRIC OTTO CIRCLE's Home Page"




No comments:

Post a Comment