Hi,
Sometimes I found it very convenient to use STL in my application.
But one thing I hate is that STL containers throw exceptions. Because
we handle errors explictly in our application, we don't want
exceptions.
Solution to that conundrum is to wrap each and every operation with
STL into a try/catch and return error code equivalent to caught
exception (or whatever you use to signal errors) from catch.
And if you do use STL, you can't e.g. rig operator new to return null
on failure, because that will cause your code to invoke UB if
allocation inside an STL container fails.
I want to know whether there's any possibility to turn exceptions off,
just like the "new(std::nothrow)" option.
Specifically, will the following operation throw exceptions? How to
handle it without the "try, catch" clause?
Fair enough
. Hard call for a question like yours.
Answer is: no. STL does not function correctly without exceptions, and
so do most part of standard C++ library. For example, STL's interface
depends on exceptions to function. Look at:
some_vector.push_back(data);
Imagine, now, that copy ctor of data's type throw. What do you do?
Imagine, further, that re-allocation, that might be needed, fails. How
would you signal that? STL is simply not made for that. To correctly
handle various failure modes in generic containers, but _without_
exceptions, you need _entirely_ different interface.
Apart from that, constructors (e.g. your string example) need
exceptions, and operator overloading needs exceptions.
(Strong personal opinion follows) Conclusion: there is __absolutely no
C++ without exceptions__. Put up or get out
.
Or... There is, if you rig memory allocation failure to e.g. terminate
your process, so that you can say that this failure doesn't happen
(not in the spirit of C or C++ languages, that move). And if you
abstain from using pretty much any C++ library. And if you can
guarantee that at least no copy constructor of any type you use can
have a failure mode. (and there's probably more conditions I can't
think about).
IOW, you're doing it wrong©, because C++ without exceptions is a crime
against humanity. (Which is not to say that specifically-crafted
parts, e.g. particularly perf. demanding, low-level code, or code
exposed to outside world through shared libraries, can't or shouldn't
be exceptions-free).
Darn... I didn't resist the urge not to speak in favor of exceptions,
did I?
Goran.