Re: Exception handling. Extension request
Oleg wrote:
Hello!
In current C++ language exception handling is defined with well
structured exception hierarchies in mind. In this case exception
handling is simple: catch(base_exception& e) and be happy.
Problem arises when one have to handle many unrelated exceptions
that does not correspond to single hierarchy or even in a not so rare
case where one needs to provide different responses for different
exceptions in the same hierarchy.
The first is common on subsystem boundaries like C++ - C or C++ - GUI
event handlers. The second is common in system-level errors handling
as it is in boost::filesystem library.
..
But I believe that the problem mentioned can be elegantly solved on
a language level. All we need is just allowing the following:
class A {};
class B {
public :
B(A const& a);
};
void foo()
try {
throw A;
} catch (B b) {
//caught
}
The idea behind it is simple: if A was thrown and B can be constructed
from it then the catch(B b) handler is called.
The gist of this proposal is to allow implicit type conversions when
catching a thrown exception. In other words, if a type A object is
thrown, and provided that type A can implicitly convert to type B (say
via a converting constructor in B or a conversion operator in A) than a
handler that catches a B object will also catch the A object thrown.
While implicit conversions are no doubt convenient (when the conversion
is intended), they can be very inconvenient (to say the least) whenever
the conversion is completely unexpected. In a way, in order to get just
the "right" conversion from A to B in this example, it is necessary to
open the door for any potential conversion - A may implicitly convert
to C, D, and E as well.
Unlike a subclass of A, which "is-a" an object of its base class, there
is no inherent (or readily apparent) relationship required between
implicitly convertible types. Practically any type can be made to
convert to another, just by supplying the appropriate method. Therefore
a programmer working with exceptions would simply have to "know" which
of B, C, D, E handlers may catch a thrown A object due to implicit
conversion. With any catch statement potentially catching almost any
thrown type, the complexity of exception handling and the burden of
knowledge on the programmer would rise sharply.
The current criteria for catching an exception (by type or by a derived
type) seem more reasonable. If a program wants to catch an A exception,
then it should catch an A object or a subclass of A. And if the program
wants that A object to be caught as a B object, then it should catch
the thown exception as an A object, construct a B object from it, and
then throw the B object.
Greg
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]