Class hierarchy of exceptions (Ada, C++)
From: Ludovic Brenta (ludovic.brenta_at_insalien.org)
Date: Sat, 26 Mar 2005 11:19:18 +0100
Robert A Duff writes:
> Well, actually, during the Ada 9X design I tried to push for a
> class-hierarchy of exceptions. I don't like every detail of the way
> C++ does it, but at least in *this* regard, it's better than Ada.
> Jerry Coffin is wrong that Ada does not allow attaching information
> to exception, by the way. Ada allows attaching Strings, which is
> admittedly a kludge. Using the class-hierarchy, as Jerry advocates,
> would be cleaner, and type safe.
I kind of like Ada exceptions as they are now. Because one cannot
carry much information in them (apart from the kluge you mentioned),
one tends not to rely on them for the normal flow of operations. I
have seen Java programs that would rely on exceptions for all kinds of
things, leading to spaghetti code. In C++ I find it a bit odd that I
can throw and catch an entire hash table as an exception if I want to.
The C++ way of catching all exceptions of a class and its derived
classes can lead to confusion. One can have multiple exception
handlers for the same exception and it may not be immediately obvious
to the reader which one is called. I see this as a maintenance
Another concern of mine with exception classes is that they'd have to
be allocated on the heap. There are situations where there is no heap
to allocate from, or where dynamic allocation is forbidden. I think
it necessary to provide a simple exception mechanism that does not
require any dynamic allocation, much less dynamic dispatching.
Perhaps a good middle-ground would be an addition to Ada along the
package Ada.Exceptions.Extra is
type Extra_Information is abstract tagged null record;
procedure Raise_Exception (E : in Exception_Id;
Information : in Extra_Information'Class);
function Exception_Information (X : Exception_Occurrence)
Programs that want to carry rich information with exceptions would be
allowed to do so, while "pragma Restrictions (No_Dispatch)" or
"No_Dynamic_Allocation" would guarantee, to those interested, that no
such thing happens.
I am aware that all this would require the compiler to provide two
exception mechanisms and two kinds of Exception_Occurrences, so I may
have opened a can of worms here. Just thinking out loud :)
-- Ludovic Brenta.