Re: throwable .vs. non throwable?
On Wed, 25 Jul 2007 07:37:06 -0700, James Kanze wrote:
On Jul 25, 2:07 pm, rpbg...@yahoo.com (Roland Pibinger) wrote:
class DataBase {
// ...
Connection* getConnection (...) throw (SQLException);
};
Without more details, that looks more like an example of where
they don't work, and should be avoided. (I'd be very surprised
if a function as complex as getConnection could not throw
anything but SQLException---that it couldn't throw bad_alloc,
for example.) From appearances (admittedly superficial, but all
I've got to go on here), you are trying to guarantee that
getConnection will throw SQLException in case it detects an
error (and can't create the connection). Regretfully, exception
specifications can't and don't guarantee that; all it says (as a
comment) is that the function might throw an SQLException,
under some undetermined conditions (but then again, it might
not). All it really says is that regardless of what happens,
this function guarantees that it will not throw any other type
of exception---generally, not a very useful bit of information.
The information that one and only one type of exception may be thrown
is useful for me as client/user of the library function (I could e.g.
retry to establish the connection). Admittedly, it cannot be specified
under which circumstances the exception is thrown. Function
declarations can only hint semantics.
They are part of the contract between implementor and user. In this
respect they are very useful.
Becareful about interpreting the contract, however. It's a
negative contract: the function will not throw anything not
listed, and not that it will throw what is listed (much less
that it will throw it when it should). Just knowing that
DataBase::getConnection might throw SQLException, under some
unspecified conditions, doesn't tell me enough to be useful for
anything; I still need the documentation concerning the
conditions under which it will throw this exception. And once
you've documented that, the extra exception specification
doesn't add any new information.
The function (obviously inspired by JDBC) lacks some documentation
which writes down that the function either returns a (pointer to a)
valid connection or throws an exception of type SQLException.
Exception specifications make the interface narrower (= better) for
the user which is an advantage.
--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch