While your
program is running, you may encounter a problem that is unexpected. This problem
can bring down the whole system. For example, your program may want to access a
file that does not exist or, is in another directory. What would happen if your
program is computing the average of a series of numbers, but the counter
(denominator) is zero or becomes zero, or what happens to your program when it
requests more memory than compiler can provide? Obviously these are unexpected
situations that rarely happen and if they occur in an unguarded program, they
may cause severe consequences. The strategy to handle errors is to provide a
systematic way of detecting them and take the necessary actions to fix them and
recover the program.
You may have
already taken proper measures to combat the errors in your program simply by
using an if-statement accompanied by a display message. The introduction of the assert(
) function from header #include <cassert>
is more advanced and takes advantage of the system error messages and aborts the
program upon an unwanted situation. One
might argue that the assert( ) function
will not be able to recover from the bug. Rather than aborting the program, you
can take a different action when the bug occurs. A more sophisticated and
systematic approach for error handling is known as exception
handling that was introduced by ANSI-C++ standard and added to C++. It is
called an exception since it is unlikely to happen, but when it does happen it
may produce unwanted results. Exception handling consists of enclosing the code
that may result in an exception in a try
block and if an exception occurs it is thrown. The statement that handles the
exception is inside the catch block.
After an exception is thrown (raised), normal control flow will suspend and the
program will search for a match or a portion of the program that can handle the
exception. After the exception is handled the program will either terminate or
resume normal execution after the corresponding catch block.
Use of exception
handling can separate error reporting from error handling and as a result
handling errors becomes systematic and readable.
In conclusion,
use of exception handling does not guarantee that errors will not occur. There
is no guaranteed solution in preventing errors. One should consider having a
fault tolerance system.