|
Dedication: Several authors, including myself, generated posts like this one a couple of years back on devshed forums. The intent of the posts was to help both novice and expert programmers, and they were written by volunteers. This post is therefore dedicated to Thaminda, the site admin at devshed who saw fit to claim ownership of the material and reposted it under his (or her) own name without any attribution or acknowledgement and (worse) making it completely pointless for the authors to correct any errors in the original posts. — Grumpy — |
Exceptions
Before getting into advanced concepts related to using exceptions, I'll describe the basics. Most of the following may be gleaned from basic texts, although I've worded things slightly differently. This material starts with basics, and becomes moderately advanced. Basic knowledge of C++ syntax is assumed.
Exceptions, as an error reporting and recovering mechanism, are a feature of C++ (not C).
As described in many texts, the basic usage comes down to
try
{
if (some_condition)
{
ExceptionType x;
throw x;
}
}
catch (ExceptionType x)
{
// recover from error
}
Core features of exceptions include:
The following is what one may normally work out by reading most basic texts. The problem is, while the material is accurate, it does not represent how one may effectively use exceptions. In particular, most people attempting to manage exceptions in their code sprinkle try/catch clauses everywhere. This actually makes their code much more complicated than it needs to be and, because try/catch blocks must wrap other code, makes their code much more difficult to understand and maintain. Ironically, it turns out that a basic rule of thumb to using exceptions effectively is that use of try/catch should be avoided wherever possible. This allows most error handling code to be localised and reduces phenomena of having to reuse exception handling code. The purpose of the remainder of this post is to explain concepts and techniques that help reduce the need to write lots of exception handling code.
The features are exhibited in the following sample.
#include <string>
class X
{
public:
int Type() const {return 1;};
};
class Y : public X
{
public:
int Type() const {return 2;};
};
;
class Other {};
void FunctionThatThrows() throw (X)
{
Y y;
throw y; // OK; Y is derived from X
}
void AnotherFunctionThatThrows() throw (X)
{
Other a;
throw a; // will result in call to abort();
}
void IntermediateFunction(bool call)
{
std::string hello("Hello");
// Just to illustrate how to do it, we catch all exceptions and rethrow them.
// Such a construct gives the same effect that the compiler would give us
// anyway
try
{
if (call) FunctionThatThrows();
// the string hello will be cleaned up (i.e. destructed) under all circumstances.
// if an exception is not thrown (eg call is false) it will be cleaned up.
// if an exception is thrown (eg call is true) it will still be cleaned up.
}
catch (...)
{
throw; // rethrow exception
}
}
int main()
{
try
{
std::string x("x");
IntermediateFunction(false);
std::string y("y");
// both x and y will be cleaned up
}
// no exception thrown, so neither of the catch clauses will be invoked
catch (X &x)
{
std::cout << x.Type() << std::endl;
}
catch (...)
{
}
try
{
std::string x("x");
IntermediateFunction(true); // this will throw
std::string y("y"); // so this line is never executed
// but x will still be cleaned up (i.e. it's destructor will be invoked).
}
// an exception of type Y (derived from X) will be thrown, so the first
// catch clause will have effect
catch (X &x)
{
std::cout << x.Type() << std::endl; // exception of type Y thrown, so value of 2
printed
}
catch (...) // catch clauses checked in order they are declared.
// First clause matches, so this one has no effect
{
}
return 0;
}
Using Exceptions
Concepts & Techniques
Lorem ipsum quaeque gubergren ne pro, per an accumsan imperdiet. Ad vis legimus adipiscing quaerendum, iuvaret facilisi sed ex, sit ei doctus lobortis. Mea instructior consectetuer eu, alia interesset ius ad. Ad habeo facilis signiferumque pro, dictas democritum vituperata quo at. In per pericula hendrerit, gubergren temporibus ea eos, has at sensibus expetenda adipiscing. Singulis postulant has cu.
Virtute tractatos in mel, malis audire prodesset in cum, vis eu hinc nominati. Sanctus scripserit ne cum, veri sapientem et duo. Has nobis blandit id. Ne eos nisl debet.
Id sed aeque paulo mediocrem. An eos invidunt sapientem, dico tota est te, quod minim verterem ex sea. Dolore civibus invenire est no. Officiis aliquyam aliquando ex vix.
In vel eros minim eligendi. Ex vix autem maiorum accusata, sit iusto definiebas ea, sint duis vocibus nec at. In duo delectus percipit petentium, odio novum repudiare ut mea. Dicta quaeque adversarium id quo. An choro elaboraret est.
Illustration of Features
Four Thangy
| Copyright © by the Contributor | Contact |