Beruflich Dokumente
Kultur Dokumente
Aims
To enable students to:
1 understand various error handling techniques
2 use function return values
3 use exceptions
function that terminates in multiple places must ensure all resources allocated
up to that point are freed, a somewhat onerous task.
It is frequently cleaner to only have one entry and exit point for a function. In
this way it is easier for a developer to ensure all appropriate resources are
freed and a maintainer to find their way around the code. Unfortunately, this
can make the function itself appear more convoluted, as in:
int iSomefunction ()
{
}
return iErrVal;
}
An alternative to the introduction of an error indicator (iErrVal in the above code) is the use
nested if statements. In uncomplicated functions this can be useful, but it is very easy for your
code to spread along way across the screen.
In an attempt to simplify error handling within source code C++ has introduced
exception handling - note the Turbo C++ compiler does not fully support this
mechanism. Exceptions remove the need for explicit checking of function
return codes, instead a single block of code is placed at the end of a function
and is called by the compiler if any called functions fail. A typical piece of code
appears as:
int iSomefunction ()
{
try
{
return 0;
}
catch ()
{
return -1;
}
}
Use exceptions
In order to process an exception your code needs a catch block. These
portions of code can be written to handle exceptions from a specific class, as
in:
catch (CMyObject)
{
}
which will handle those raised by the CMyObject class, or generic in which
case no class name is provided in the catch statement.
If an exception is raised within a function that has no handler, then the failure
is passed down the stack of executing functions until a handler is met that can
cope with it. If none is found then the process is terminated.
To raise exceptions a program uses the throw statement, which is very similar to return.
For example, to throw and catch a simple error message the following code may be used:
try
{