Handling errors
A robust application of CPLEX in C++ avoids errors with assertions and handles unforeseeable errors with exceptions.
Concert Technology provides two lines of defense for dealing with error conditions, suited for addressing two kinds of errors. The first kind covers simple programming errors. Examples of this kind are trying to use empty handle objects or passing arrays of incompatible lengths to functions.
This kind of error is usually an oversight and should
not occur in a correct program. In order not to pay any runtime cost
for correct programs asserting such conditions, the conditions are
checked using assert statements. The checking
is disabled for production runs if compiled with the -DNDEBUG compiler
option.
The second kind of error is more complex and cannot generally be avoided by correct programming. An example is memory exhaustion. The data may simply require too much memory, even when the program is correct. This kind of error is always checked at runtime. In cases where such an error occurs, Concert Technology throws a C++ exception.
In fact, Concert Technology provides a hierarchy of exception
classes that all derive from the common base class IloException .
Exceptions derived from this class are the only kind of exceptions
that are thrown by Concert Technology. The exceptions thrown by IloCplex objects all derive from class IloAlgorithm::Exception or IloCplex::Exception .
To handle exceptions gracefully in a Concert Technology
application, include all of the code in a try/catch clause,
like this:
IloEnv env;
try {
// ...
} catch (IloException& e) {
cerr << "Concert Exception: " << e << endl;
} catch (...) {
cerr << "Other Exception" << endl;
}
env.end();
The construction of the environment comes
before the try/catch clause. In case of
an exception, env.end must still be called.
To protect against failure during the construction of the environment,
you can add another try/catch clause.
If code other than Concert Technology code is used in
the part of that sample denoted by ... ,
all other exceptions will be caught with the statement catch(...) .
Doing so is good practice, as it makes sure that no exception is unhandled.