Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Exceptions, Go to Hell!

15 views
Skip to first unread message

thomas

unread,
Aug 24, 2010, 2:38:39 AM8/24/10
to
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.

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?
-------------
char *p;
string str(p, 20);
-----------

(Don't teach me the benefits of exceptions)

--tom

Goran Pusic

unread,
Aug 24, 2010, 3:29:31 AM8/24/10
to
On Aug 24, 8:38 am, thomas <freshtho...@gmail.com> wrote:
> 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?
> -------------
> char *p;
> string str(p, 20);
> -----------
>
> (Don't teach me the benefits of exceptions)

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.

Andrea Venturoli

unread,
Aug 24, 2010, 3:29:48 AM8/24/10
to
Il 08/24/10 08:38, thomas ha scritto:

> I want to know whether there's any possibility to turn exceptions off,
> just like the "new(std::nothrow)" option.

Your compiler might have a switch for this.
Of course the STL won't work as expected, then, as it is supposed to
throw exceptions.
Specifically, you will never know if it fails.

> Specifically, will the following operation throw exceptions?

Possibly, unless you turn exceptions off in the compiler.

> How to handle it without the "try, catch" clause?

No way: if you turn off exceptions, you are putting your head in the
sand, just hoping it won't fail.

> (Don't teach me the benefits of exceptions)

I won't. It's just that if you want to use a library which uses
exceptions, you have to use exceptions.

bye
av.

Öö Tiib

unread,
Aug 24, 2010, 3:36:13 AM8/24/10
to
On Aug 24, 9:38 am, thomas <freshtho...@gmail.com> wrote:
> 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.

Only part of container interface may throw exceptions. If it is not
true for you then it is that implementation you use.

> I want to know whether there's any possibility to turn exceptions off,
> just like the "new(std::nothrow)" option.

STL does throw on bugs. If you do not have bugs then it does not
throw. If there is extension (like microsofts secure iterators) then
use methods of extension.

>
> Specifically, will the following operation throw exceptions? How to
> handle it without the "try, catch" clause?

Without the "try, catch" clauses. You "handle errors explictly in our
application" so the exceptions never happen.

> -------------
> char *p;
> string str(p, 20);
> -----------
>
> (Don't teach me the benefits of exceptions)

This is programming bug. What should you do? (hint: "catch it" is
wrong answer)

Ian Collins

unread,
Aug 24, 2010, 3:52:09 AM8/24/10
to
On 08/24/10 06:38 PM, thomas wrote:
> 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.
>
> I want to know whether there's any possibility to turn exceptions off,
> just like the "new(std::nothrow)" option.

Maybe, but how will you know if a failure that is reported by an
exception occurs?

--
Ian Collins

Stuart Redmann

unread,
Aug 24, 2010, 5:49:26 AM8/24/10
to
thomas wrote:
> 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.
>
> I want to know whether there's any possibility to turn exceptions off,
> just like the "new(std::nothrow)" option.

That would be quite nice. Unfortunately, C++ offers no language
feature that turns off exceptions globally. Microsoft's COM framework
uses a language-independent scheme for working with exceptions which
may come close to what you want: Exceptions in COM is basically
managed via return values; every method returns an integer error code
(in order to get the actual exception object with all the detailed
information, you'll have to query COM's run-time environment). Even
though this scheme takes the freedom of choosing the return type of a
method, COM lets you declare a "retval" parameter. When you use the
COM method in client code, the MS's Visual C compiler generates two
methods: one that uses the usual error code as return value and one
that acts like a wrapper: it will translate the usual error code to
exceptions and will return the "retval" parameter. This is quite handy
since it is up to you which method you want to use.

Regards,
Stuart

Stuart Redmann

unread,
Aug 24, 2010, 6:07:06 AM8/24/10
to
> On Aug 24, thomas wrote:
> > 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.
[snip]

> > 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?
> > -------------
> > char *p;
> > string str(p, 20);
> > -----------
[snip]

Goran Pusic wrote:
> 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.

[snip]

That's a good argument. I guess that nobody wants to establish a
scheme for propagating errors for containers other than the exception
mechanism because such a scheme would be quite ugly. Unfortunately, C+
+ does provide little support for exception specifications inside
templates: There is no way how I can tell C++ that the type inside
some container will not throw any exceptions at all, so that the
interface of the fully typed container will only expose those
exceptions that stem from the container code. For example, if I have a
type T which may throw an exception E when being copy-constructed, I'd
expect that std::vector<T> has an exception specification like this:
std::vector<T>::push_back (T&) throw (E, out_of_memory_exception).
If I use a type U that throws no exceptions upon copy-construction,
this should be
std::vector<U>::push_back (U&) throw (out_of_memory_exception)
[This is quite probably very wrong, but you get the idea].
Were we able to change the exception specification depending on a
template parameter, we could change STL's vector::push_back interface
in such a way that it could only return error codes for errors that
occur due to the implementation of vector::push_back, like
EPushBackError vector<T>::push_back (T&)
with
enum EPushBackError
{
ERROR_OUT_OF_MEMORY
};

Unfortunately, no such thing exists in C++ (nor in any other language
I know, not even Ada95).

Regards,
Stuart

Jorgen Grahn

unread,
Aug 24, 2010, 6:56:16 AM8/24/10
to
On Tue, 2010-08-24, thomas wrote:
> 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.

Don't they just use exceptions for out-of-memory situations, just like
operator new? (Plus some special cases like std::vector<T>::at(),
which you don't have to use.)

So if you use operator new already, the containers really don't make
exceptions more of a problem.

Also note that for many applications, catching out-of-memory up in
main() and exiting is enough.

> I want to know whether there's any possibility to turn exceptions off,
> just like the "new(std::nothrow)" option.

With g++, the containers will be unusable with exceptions turned off
-- your code won't compile. Don't know about other compilers, but I
fail to see how they can avoid using exceptions.

> Specifically, will the following operation throw exceptions? How to
> handle it without the "try, catch" clause?
> -------------
> char *p;
> string str(p, 20);
> -----------

Huh? The bug there isn't something that will be reported as an
exception. It will just crash -- if you're lucky.

/Jorgen

--
// Jorgen Grahn <grahn@ Oo o. . .
\X/ snipabacken.se> O o .

Goran Pusic

unread,
Aug 24, 2010, 7:19:48 AM8/24/10
to
On Aug 24, 9:36 am, Öö Tiib <oot...@hot.ee> wrote:
> STL does throw on bugs. If you do not have bugs then it does not
> throw.

That's too simplified. It throws on failed allocations and of course,
it does not try to be smart with exceptions from assignment operators
or copy constructors for user types.

Goran.

Öö Tiib

unread,
Aug 24, 2010, 7:38:15 AM8/24/10
to

Allocator may throw something and your types you use in container may
throw something. Can it be called that "container throws". I don't
think so. So ... maybe not everything what is left are bugs ... but i
do not remember anything. Refresh me.

Daniel T.

unread,
Aug 24, 2010, 7:46:02 AM8/24/10
to
thomas <fresh...@gmail.com> wrote:

I worked in a shop like that once. We wrote our own string, vector and
map classes that had the same interface as the STL classes (our string
class was cleaner though,) and any situation where the standard class
would have thrown an exception, our classes aborted.

You don't need to go that far though, just treat every situation where
an exception is thrown as a pre-condition violation.

w...@seed.net.tw

unread,
Aug 24, 2010, 8:13:22 AM8/24/10
to
On 8月24日, 下午3時29分, Goran Pusic <gor...@cse-semaphore.com> wrote:
> On Aug 24, 8:38 am, thomas <freshtho...@gmail.com> wrote:
>
> > 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.
>
In addition, user's type used in a container should not throw the
same
type as the container declares to throw, otherwise the catch handler
could be confused what is really 'caught'.
Furthermore, nearly all types thrown should be in a way distinct.

Goran Pusic

unread,
Aug 24, 2010, 8:23:24 AM8/24/10
to

If I am not mistaken, STL code will indeed throw because of:

1. a bug
2. OOM

(I agree, it's unfair to say that STL threw if actually user code
threw).

So ultimately, one could say that STL only throws due to OOM. That's
enough for me :-).

Goran.

peter koch

unread,
Aug 24, 2010, 8:31:21 AM8/24/10
to

The default behaviour is to throw an exception when you are out of
memory.
Simply set a new_handler that aborts when it is out of memory. Out of
memory will not be an error that you want to test for in most types of
code anyway.

/Peter

Goran Pusic

unread,
Aug 24, 2010, 8:32:17 AM8/24/10
to
On Aug 24, 1:46 pm, "Daniel T." <danie...@earthlink.net> wrote:

That's quite alright, except that it's not really nice to abort on
bad_alloc in particular. That's almost always too harsh.

It's only OK if the whole program is one "do work" iteration, and even
then, it cost little to write one catch in main(), e.g.

int main()
{
try { return work(); }
catch(const exception& e) // perhaps bad_alloc, perhaps something
else.
{ return error_code_from_exception(); /*nothrow guarantee here*/ }
}

Goran.

Öö Tiib

unread,
Aug 24, 2010, 9:08:16 AM8/24/10
to

And handling OOM may have catch(std::bad_alloc&) in main() and maybe
in bigger memory consuming operations. Memory of computer is full so
what is there to do in function that did std::vector::push_back() ?
Nothing. End of world disaster for it. It must watch from side how it
flies.

Juha Nieminen

unread,
Aug 24, 2010, 9:54:55 AM8/24/10
to
Stuart Redmann <DerT...@web.de> wrote:
> thomas wrote:
>> 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.
>>
>> I want to know whether there's any possibility to turn exceptions off,
>> just like the "new(std::nothrow)" option.
>
> That would be quite nice.

Exactly how would that be "quite nice"? What do you suggest the containers
do in case of an error? Silently misbehave? Something else? What?

When you start thinking about how you would be able to detect any
possible errors with STL containers, you will find that exceptions are,
in fact, the *easiest* and most practical way of doing that. Any other
method you might think of (such as putting an error code somewhere which
you would have to check) would result in much more complicated code from
your part and, more importantly, would result in significantly more
error-prone code (because you *will* forget to check such error codes).

Of course a data container silently misbehaving in case of error would
be the worst possible solution. By far.

RB

unread,
Aug 24, 2010, 10:24:52 AM8/24/10
to
Hi Goran, ( I am assuming you are the same Goran that used to help
me on ms.public.vc.mfc before ms shut down the server )
I have studied exceptions quite a bit since you and Joe patiently
helped me. Though still much a novice dummy overall, from what
I have learned on exceptions I agree with your post.
It would appear to me that either you would have catch and handle
or swallow with "a catch and do nothing" if you were confident that your
callers error handling code could rectify the violation effects.
OR else have the results in your face OR in your back down the road.
I have a question at this point (hopefully I am posting this before the
Belgium time zone sleeps) and that is "exception specifications".
I.e if I define a function as:
int MyFunc( int Arg1, DWORD Arg2) throw( ) {.........}
(which according to data read would in some cases denote this function
would not throw "any" exception)
Albeit I don't see how they could be a solution for the OP since he is
dealing with a library already coded, I still have mixed information as to how
reliable they actually are and even more so, I've read that some modern
version compilers ignore them.
Given the inherent underlying hardware interrupt and OS implementation
it would seem that if you deny "some" exception handlers from taking place,
your machine would either blue screen crash or take off on an endless loop.
While lesser infractions would let the function or application or machine limp
along until a corruption is exposed and causes a failure of related consequence.
What is your knowledge on this.
Further for your comment or correction a few current concepts of mine.
1. Any exceptions thought of "not needed to be caught" would have to
be coded (in a perfect program) so that the exception never happens.
And debuggers can help make this more of a conceivable reality.
2. But debuggers cannot prevent a user opening the wrong file or
wrong format, or a third party lib foo bars or any other scenario that is
out of the control of the end product programmer.
3. It would appear that exceptions are a reality that hardware and OS
engineers deemed necessary to promote their product as more stable.
Even with the most foo bar programmer (in many cases like myself) the
underlying hardware/OS partnership brings up the crash dialog that
basically says "Your App programmer FooBarred so let him know"
Without exceptions the user sits at his screen wondering "WTF ! my
computer just broke".
4. Any exception that should be caught is one that the "error handling code
was not able to control " OR the exception structure excels as a vehicle for
covering an expanded area of code that needs to unwind, destruct, delete
and or reset items that have traversed up until the exception occured.
Good talking to you (or getting corrected for my ignorance) again. RB

RB

unread,
Aug 24, 2010, 10:27:03 AM8/24/10
to
I agree with you. Please (if you have time) comment on
my reply to Goran in other offset thread further down.

Stuart Redmann

unread,
Aug 24, 2010, 10:34:19 AM8/24/10
to
thomas wrote:
> >> one thing I hate is that STL containers throw exceptions. Because
> >> we handle errors explictly in our application, we don't want
> >> exceptions.
> >>
> >> I want to know whether there's any possibility to turn exceptions off,
> >> just like the "new(std::nothrow)" option.


Stuart Redmann wrote:
> > That would be quite nice.

Juha Nieminen wrote:
> Exactly how would that be "quite nice"? What do you suggest the containers
> do in case of an error? Silently misbehave? Something else? What?

Something that comes close to what I described in the paragraph you
decided to snip (without marking that you've done so) almost
completely. If C++ could generated two versions of the same function,
one using exceptions and one using error codes, this may be a useful
feature. Personally I don't have a problem with exceptions, even
though I think that try-catch-statements can make code unreadable
(which is why I use my personal pre-processor macros to hide them).

All I have to say is that there are cases where the user of some
library (in this case STL) wants to check every single operation, and
sometimes he may only be interested whether a lot of operations
succeeded. In the first case he'd prefer error codes, in the second
case exceptions. But noone wants to write two versions of the same
function, so it would be nice if C++ could generate two versions of a
function from a single definition (like the #import'ed type libraries
under Visual Studio).

Regards,
Stuart

Goran Pusic

unread,
Aug 24, 2010, 10:38:37 AM8/24/10
to
> And handling OOM may have catch(std::bad_alloc&) in main() and maybe
> in bigger memory consuming operations. Memory of computer is full so
> what is there to do in function that did  std::vector::push_back() ?
> Nothing. End of world disaster for it. It must watch from side how it
> flies.

Well, no, not really. You see, it all depends on what program does. If
program is one iteration of some work, then OOM is indeed the end of
the world.

But if the program is almost anything else, it isn't. Because,
typically, what happens is that code embarks on some path, allocates,
calculates (rinse, repeat)... When done, it cleans up whatever is
auxiliary and keeps some form of result (even if it is some
modification of the global state. Now... If said code path ends
happily, there probably was a peak on resource usage somewhere in the
middle, and then, when going back some of these resources were freed
(any temporary resources). If code path steps on resource shortage, it
has to go up the stack (or better yet, I should say something like
"resource allocation chain") and free any resources it obtained in the
meantime.

In both cases (and especially in a failure case), once code path is
"unwound", there __are__ resources available. Whether it's then
interesting to start some new operation or not, what do I know. But I
know that e.g. a well-behaved editor-type program, if it can't do some
manipulation on my document because of resource shortage, should not
just die in the middle of that operation. It should, instead, rewind,
and say "whoops, can't do that" and let me save what I have up to
now :-). Similar goes to a lot of other program types (e.g. a server-
type app: - request comes in, but there's no resources to fulfill
that particulars request - so drop a bomb on that request and clean
up, but continue serving other clients). It's only straight-line code
that benefits ( a little :-) ) from immediate death on resource
shortage.

Goran.

RB

unread,
Aug 24, 2010, 10:45:02 AM8/24/10
to
I agree with you. And even so the compiler switch does not actually turn
off exceptions from happening (as I am sure you are aware of ) but rather
only turns off the ability for SEH type exceptions from being caught in the
compiled code. The final CRT caller and/or OS handler will still put a crash
dialog in my face if the violation is serious enough. And if it is a lesser infraction
my app continues along like a person with colon cancer but no colonoscopy test
to tell him it needs removed. I'm sure you can guess the results of that scenario.
But admittedly the OP says that his calling code takes care of any errors.
And I don't doubt his competence which is probably much higher than mine.
What I do doubt (from within my competence level ) is how his calling code
is going to cover uncontrollable items that may happen while inside the STL lib ?
Is his error covering code going to be able to back out of STL, destruct any
allocated items and reset any items that have traversed to current expecting
completion ? Granted a good lib ( like STL ) would do that on it's own BUT
the vehicle for doing so would be exceptions.

Goran Pusic

unread,
Aug 24, 2010, 10:54:07 AM8/24/10
to

I suggest you take a look at what Herb Sutter has to say on exception
spec (basically: they way they are defined by C++, are useless :-) ).
(Search gotw.ca for "throw()" ). His explanation is much better than
anything I can come up here. :-)

> Further for your comment or correction a few current concepts of mine.
> 1. Any exceptions thought of  "not needed to be caught" would have to
>     be coded (in a perfect program) so that the exception never happens.
>     And debuggers can help make this more of a conceivable reality.
> 2. But debuggers cannot prevent a user opening the wrong file or
>     wrong format, or a third party lib foo bars or any other scenario that is
>    out of the control of the end product programmer.
> 3. It would appear that exceptions are a reality that hardware and OS
>     engineers deemed necessary to promote their product as more stable.
>     Even with the most foo bar programmer (in many cases like myself) the
>     underlying hardware/OS partnership brings up the crash dialog that
>     basically says "Your App programmer FooBarred so let him know"
>     Without exceptions the user sits at his screen wondering "WTF ! my
>     computer just broke".

Well, I am not so sure about that. To me, exceptions are a way to
__structure code in face of unexpected situations__. They are not
there to "handle errors", and they are certainly not there to somehow
handle __coding errors__ (that's IMO a massive error many people
make).

And indeed, if you look at your OS, it does __not__ emit any
exceptions in C++ sense (nor in any other language sense, really). Not
even Windows does that. When you receive windows exception (SE one),
your code is already dead.

Effectively, exceptions help you to eliminate a myriad of error code
paths and transport error info to a place where you can do something
about that error. No more, no less. In a way, when speaking about
exceptions, I often say "forget error __handling__, there is no such
thing". Because, what we call error handling, exceptions or not, is
almost always "clean up and get out, report error to some external
factor". It's _resource handling_ (and sometimes, program state
handling), on one hand, and _error reporting_, on the other. 'cause,
situations where error happens and code can correct it, are __rare__.
And that's the ultimate reason why exceptions are so good - they help,
massively, in handling common situation where, upon error, all you can
do is to clean up and get out.

> 4. Any exception that should be caught is one that the "error handling code
>     was not able to control " OR the exception structure excels as a vehicle for
>     covering an expanded area of code that needs to unwind, destruct, delete
>     and or reset items that have traversed up until the exception occured.

This part I don't understand, sorry.

Goran.

Francesco S. Carta

unread,
Aug 24, 2010, 10:54:29 AM8/24/10
to
RB <NoMail@NoSpam>, on 24/08/2010 10:24:52, wrote:

<snip>

Sorry for dropping in with such a request, but you should really do
something about the formatting of your posts. Reading them is far from
comfortable.

Assuming you're doing this: please avoid breaking lines when you reach
the edge of your screen.

Assuming you're not doing this: please separate your paragraphs with two
"enter" keystrokes.

I seem to recall that you have set your (weird) newsreader (Outlook 6)
with some large line-length and that you have some sort of issue with
mixed end-of-line markers.

I strongly advice you to get a better newsreader.

Shall you need help about this feel free to ask either here or via
private email, and many people will avoid some headaches.

--
FSC - http://userscripts.org/scripts/show/59948
http://fscode.altervista.org - http://sardinias.com

tni

unread,
Aug 24, 2010, 11:12:32 AM8/24/10
to
On 2010-08-24 14:32, Goran Pusic wrote:
> That's quite alright, except that it's not really nice to abort on
> bad_alloc in particular. That's almost always too harsh.
>
> It's only OK if the whole program is one "do work" iteration, and even
> then, it cost little to write one catch in main(), e.g.
>
> int main()
> {
> try { return work(); }
> catch(const exception& e) // perhaps bad_alloc, perhaps something
> else.
> { return error_code_from_exception(); /*nothrow guarantee here*/ }
> }
>
> Goran.

That only works if you write exception safe code. If you don't (and I
have the distinct impression the OP doesn't want to), you want to abort.

If you have an OS that overcommits memory, you very likely won't get a
bad_alloc anyway.

Öö Tiib

unread,
Aug 24, 2010, 11:40:31 AM8/24/10
to
On Aug 24, 5:38 pm, Goran Pusic <gor...@cse-semaphore.com> wrote:
> > And handling OOM may have catch(std::bad_alloc&) in main() and maybe
> > in bigger memory consuming operations. Memory of computer is full so
> > what is there to do in function that did  std::vector::push_back() ?
> > Nothing. End of world disaster for it. It must watch from side how it
> > flies.
>
> Well, no, not really. You see, it all depends on what program does. If
> program is one iteration of some work, then OOM is indeed the end of
> the world.

I said OOM is end of the world for ordinary function that did
something that may cause some allocation, in my example
std::vector::push_back(). Grep for "push_back" in some C++ code base
to identify them. So it should keep its hands in pocket and not touch
std::bad_alloc. It is way ower head issue for it. I did not say that
it is likely end of world for a *program*.

If your program contains operations that may be too memory consuming
and whose failure is not end of the world for whole application then
put catch(std::bad_alloc const&) around these too. Can say to user
that "kill some other apps and try again". But i see i mentioned that
too in the piece you quoted above.

RB

unread,
Aug 24, 2010, 12:03:09 PM8/24/10
to
>> "exception specifications"...................

>I suggest you take a look at what Herb Sutter has to say on exception
>spec (basically: they way they are defined by C++, are useless :-) ).
>(Search gotw.ca for "throw()" ). His explanation is much better than
>anything I can come up here. :-)

Thanks will do that soon.

> > 3. It would appear that exceptions are a reality that hardware and OS

> > engineers deemed necessary .......................

>Well, I am not so sure about that. To me, exceptions are a way to
>__structure code in face of unexpected situations__. They are not
>there to "handle errors", and they are certainly not there to somehow
>handle __coding errors__ (that's IMO a massive error many people
>make).

Well I totally agree with your above sumation, BUT what I was attempting
to say was "all " of the exception ability (even c++ ) is created (albeit expanded)
on top of the basic provided by the hardware interrupt system and OS partnership
of the linked list of handlers at FS:[0]. That said I was stating the "origin" of said
capability was (as I see it ) the promotion of a more stable computer product
(or least an informed exit ) as opposed to an unlabeled crash.

> And indeed, if you look at your OS, it does __not__ emit any
> exceptions in C++ sense (nor in any other language sense, really). Not
> even Windows does that. When you receive windows exception (SE one),
> your code is already dead.

Well no I must have been ambiguous, since I did not mean that the OS would
implement an exception frame that would comply with the trylevel and scopetables
of the C compiler's SEH or the similar but syncronous C++ with trylevels only and
no scopetable implemenation. But the OS itself can also have uncontrollable aspects
that it may it may have to emit (throw) an exception on it's own, OR handle an a
hardware violation from the hardware interrupt table, if the running process doesn't
handle it first. And as for your code being dead already, of course in most cases the
programmer cannot be aware enough of the voilation code to reset a null pointer (etc)
in the Context structure and return a continue_execution at the same violating address.
And even if it the progammer was aware it would ( I think ) be more appropriate to
rather use such an exception as an opportunity to implement a a crash report and a
polite exit. Then use such to create a code update.

> > 4. Any exception that should be caught is one that the "error handling code
> > was not able to control " OR the exception structure excels as a vehicle for
> > covering an expanded area of code that needs to unwind, destruct, delete
> > and or reset items that have traversed up until the exception occured.

> This part I don't understand, sorry. Goran.

Ok, well apologize for ambiguity on my part, but in many ways I am attempting
to say the same concept as your post on an above thread repasted below,

James Kanze

unread,
Aug 24, 2010, 12:25:07 PM8/24/10
to
On Aug 24, 2:54 pm, Juha Nieminen <nos...@thanks.invalid> wrote:

[...]


> When you start thinking about how you would be able to detect
> any possible errors with STL containers, you will find that
> exceptions are, in fact, the *easiest* and most practical way
> of doing that.

Independently of easiest or most practical, exceptions are the
way the standard library expects errrors like insufficient
memory to be reported. Within the library, when the code calls
an allocator, it doesn't test whether the allocator returned
null or not; it supposes that the pointer it got back is good
(and that if the allocation failed, an exception was raised, so
that the library doesn't have to deal with it later).

One can conceive of other solutions (although as you say,
they're likely to be more complicated), but that's the solution
the library uses, and it doesn't work any other way.

--
James Kanze

Andrea Venturoli

unread,
Aug 24, 2010, 1:24:01 PM8/24/10
to
Il 08/24/10 16:45, RB ha scritto:

> What I do doubt (from within my competence level ) is how his calling code
> is going to cover uncontrollable items that may happen while inside the
> STL lib ?
> Is his error covering code going to be able to back out of STL,
> destruct any allocated items and reset any items that have
> traversed to current expecting completion ?

That question is bad posed: stripping off exceptions doesn't make an
interface grow any other mean of communicating problems.
So you can't treat them, since you don't know they are there.

bye
av.

Kai-Uwe Bux

unread,
Aug 24, 2010, 3:35:03 PM8/24/10
to
Daniel T. wrote:

> thomas <fresh...@gmail.com> wrote:
>
>> 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.
>>
>> 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?
>> -------------
>> char *p;
>> string str(p, 20);
>> -----------
>>
>> (Don't teach me the benefits of exceptions)
>
> I worked in a shop like that once. We wrote our own string, vector and
> map classes that had the same interface as the STL classes (our string
> class was cleaner though,) and any situation where the standard class
> would have thrown an exception, our classes aborted.

[...]

The OP made me think about that. I wonder: couldn't you do that via a custom
allocator (maybe even an allocator adaptor) instead of doing it over and
over for each container?


Best

Kai-Uwe Bux

Daniel Pitts

unread,
Aug 24, 2010, 4:48:39 PM8/24/10
to
On 8/23/2010 11:38 PM, thomas wrote:
> 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.
>
> 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?
Don't put in a try/catch block, and let your program abort.

> -------------
> char *p;
> string str(p, 20);
> -----------
This snipped is undefined behavior, with or without exceptions.

The funny thing about out-of-memory exceptions, is that often the only
thing you *can* do is abort. There are some situations where you can
successfully recover, but you better not be using threads, and you
better have a comprehensive recovery strategy.


>
> (Don't teach me the benefits of exceptions)

While I cannot teach you something you are unwilling to learn, I will
express that exceptions are necessary, not just beneficial, to
programming in C++. In other words, I won't teach you the benefits, but
know it is a necessity.

--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>

Goran Pusic

unread,
Aug 25, 2010, 3:35:02 AM8/25/10
to
On Aug 24, 5:12 pm, tni <t...@example.invalid> wrote:
> On 2010-08-24 14:32, Goran Pusic wrote:
>
> > That's quite alright, except that it's not really nice to abort on
> > bad_alloc in particular. That's almost always too harsh.
>
> > It's only OK if the whole program is one "do work" iteration, and even
> > then, it cost little to write one catch in main(), e.g.
>
> > int main()
> > {
> >    try { return work(); }
> >    catch(const exception&  e) // perhaps bad_alloc, perhaps something
> > else.
> >    { return error_code_from_exception(); /*nothrow guarantee here*/ }
> > }
>
> > Goran.
>
> That only works if you write exception safe code. If you don't (and I
> have the distinct impression the OP doesn't want to), you want to abort.

Heh, that's very true. However, aborting is a massively substandard
coding (to me at least, and especially in C++, where language
capabilities - think RAII - make any recovery a breeze). And e.g. no
library code should ever do it, 'cause it's not library writer's
choice to make.

On top of that, both exceptions and premature returns require similar
approach to coding. Premature return is effectively very simple coding
strategy, e.g. (using ScopeGuard and counting absence of any other
resource handling class):

RESULT_TYPE f(params)
{

RESOURCE_TYPE1 r1 = alloc1();
ON_BLOCK_EXIT(free, r1);

// rinse, repeat this, add more resources
RESULT_TYPE r = call1(params);
if (failed(r))
{
assert(0);
return r;
}
// By the way, you can wrap 6 lines above in a macro, so you get
e.g.
// CHECKED(RESULT_TYPE, call1(params));

RESOURCE_TYPE2 r2 = alloc2();
ON_BLOCK_EXIT(free, r2);

...
return RESULT_TYPE(SUCCESS);
// Any resources freed automaticaly by scope guards
}

(It's similarly simple if some resource(s) should be a e.g. return
value or kept for later in some global state, but then one would use a
Make(Obj)Guard and "Dismiss").

All in all, exceptions or not, in C++, code that is exception safe is
also __extremely__ simple in form, and works correctly even if you put
exceptions out of the picture.

> If you have an OS that overcommits memory, you very likely won't get a
> bad_alloc anyway.

Yes. BTW, I hate overcommit, because large swaths of people have
experienced it and now think that handling memory correctly is
effectively futile. But that's not how C, C++, nor many other a-
language, is meant to work, not at all.

Goran.

Öö Tiib

unread,
Aug 25, 2010, 4:03:50 PM8/25/10
to
On 25 aug, 10:35, Goran Pusic <gor...@cse-semaphore.com> wrote:
>
> On top of that, both exceptions and premature returns require similar
> approach to coding. Premature return is effectively very simple coding
> strategy, e.g. (using ScopeGuard and counting absence of any other
> resource handling class):
>
> RESULT_TYPE f(params)
> {
>
>   RESOURCE_TYPE1 r1 = alloc1();
>   ON_BLOCK_EXIT(free, r1);
>
>   // rinse, repeat this, add more resources
>   RESULT_TYPE r = call1(params);
>   if (failed(r))
>   {
>     assert(0);
>     return r;
>   }
>   // By the way, you can wrap 6 lines above in a macro, so you get
> e.g.
>   // CHECKED(RESULT_TYPE, call1(params));
>
>   RESOURCE_TYPE2 r2 = alloc2();
>   ON_BLOCK_EXIT(free, r2);
>
>   ...
>   return RESULT_TYPE(SUCCESS);
>   // Any resources freed automaticaly by scope guards
>
> }

I don't understand that "assert(0)" part. It reads like "abort()" for
me and "return" after it seems unreachable code.

[...]

> > If you have an OS that overcommits memory, you very likely won't get a
> > bad_alloc anyway.
>
> Yes. BTW, I hate overcommit, because large swaths of people have
> experienced it and now think that handling memory correctly is
> effectively futile. But that's not how C, C++, nor many other a-
> language, is meant to work, not at all.

That overcommit is red herring since it can be turned off with some
kernel parameter like "vm.overcommit_memory = 0". If an user refuses
to turn it off and random apps he runs get killed randomly then it is
his fault, why should you care.

Daniel T.

unread,
Aug 25, 2010, 8:10:13 PM8/25/10
to
Goran Pusic <gor...@cse-semaphore.com> wrote:
> On Aug 24, 1:46 pm, "Daniel T." <danie...@earthlink.net> wrote:
> > thomas <freshtho...@gmail.com> wrote:
> > > 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.
> >
> > > 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?
> > > -------------
> > > char *p;
> > > string str(p, 20);
> > > -----------
> >
> > > (Don't teach me the benefits of exceptions)
> >
> > I worked in a shop like that once. We wrote our own string, vector and
> > map classes that had the same interface as the STL classes (our string
> > class was cleaner though,) and any situation where the standard class
> > would have thrown an exception, our classes aborted.
> >
> > You don't need to go that far though, just treat every situation where
> > an exception is thrown as a pre-condition violation.
>
> That's quite alright, except that it's not really nice to abort on
> bad_alloc in particular. That's almost always too harsh.

Not at all. In the shop I worked at, we had memory guarantees and using
more than our guarantee was a bug that needed to be fixed. (The app was
going to crash anyway, might as well abort.)

When a programmer started working with us, I had to recondition him and
monitor him closely until he understood that there was no virtual memory
mechanism there to save him, and he actually had to worry about
fragmentation. That seems to be a hard thing for modern programmers to
conceive of.

Daniel T.

unread,
Aug 25, 2010, 8:23:39 PM8/25/10
to
Goran Pusic <gor...@cse-semaphore.com> wrote:
> On Aug 24, 9:36 am, Öö Tiib <oot...@hot.ee> wrote:
>
> > STL does throw on bugs. If you do not have bugs then it does not
> > throw.
>
> That's too simplified. It throws on failed allocations and of course,
> it does not try to be smart with exceptions from assignment operators
> or copy constructors for user types.

Frankly, I agree with Öö Tiib. It has been my experience that if my
program threw an exception, any exception, I had to re-write it so that
it no longer threw the exception.

[From Goran in a different post]


> typically, what happens is that code embarks on some path, allocates,
> calculates (rinse, repeat)... When done, it cleans up whatever is
> auxiliary and keeps some form of result (even if it is some
> modification of the global state. Now... If said code path ends
> happily, there probably was a peak on resource usage somewhere in the
> middle, and then, when going back some of these resources were freed
> (any temporary resources). If code path steps on resource shortage, it
> has to go up the stack (or better yet, I should say something like
> "resource allocation chain") and free any resources it obtained in the
> meantime.

If the code's result is required for proper program functioning, and it
fails (throws an exception,) then the code has to be re-written so that
it won't fail anymore. If the code's result isn't required, then why
call the code in the first place?

I guess you could write a program that provides extra features if enough
memory happens to be available, but I've never had to do that, nor have
I seen a program that does.

thomas

unread,
Aug 26, 2010, 2:29:28 AM8/26/10
to

I agree.

Goran Pusic

unread,
Aug 26, 2010, 3:18:27 AM8/26/10
to
> Frankly, I agree with Öö Tiib. It has been my experience that if my
> program threw an exception, any exception, I had to re-write it so that
> it no longer threw the exception.

Even if exceptions was due to network failure that prevented a file
from being open? No, that's too harsh. That said, I agree that there
are situations where you'd say "well, this ate resources and it needs
to be rewritten".

> If the code's result is required for proper program functioning, and it
> fails (throws an exception,) then the code has to be re-written so that
> it won't fail anymore. If the code's result isn't required, then why
> call the code in the first place?

(I'll restrict my discussion to OOM conditions).

Approach you're advocating works only where you can, through external
means, guarantee that you'll have enough memory for whatever you want
to do. I'd say that reduces your set of runtime environments.

But in general, that's a tough call. Who's to prevent users from
running the code on a system with less memory? Who's to prevent the
administrator to reduce working set of the process? Who's to prevent
the user to use virtual memory up to the full? Etc. What I spoke about
(clean-up, get out, continue with something else) applies in all these
cases.

In general, there's too many factors out of your control. In my view
if bad things __can__ happen, they __will__ (I am old :-) ). So your
"there will be memory" approach does not fly all that well for me.

Goran.

Goran Pusic

unread,
Aug 26, 2010, 3:22:32 AM8/26/10
to
On Aug 24, 4:34 pm, Stuart Redmann <DerTop...@web.de> wrote:

> Personally I don't have a problem with exceptions, even
> though I think that try-catch-statements can make code unreadable
> (which is why I use my personal pre-processor macros to hide them).

Are you using RAII well? ScopeGuard?

If not, start using it.

If yes, you should have tiny mini micro number of try-catch-es in
code. If you don't, there's something wrong with the way you do
things. ( Yes, I am prick enough to say that without even knowing what
your code looks like ;-) ).

Goran.

Kai-Uwe Bux

unread,
Aug 26, 2010, 4:26:33 AM8/26/10
to
Goran Pusic wrote:

I am curious: if I use a function that communicates failure (or some other
condition) via throwing, how can RAII or ScopeGuard help me to avoid a catch
statement?


Best

Kai-Uwe Bux

James Kanze

unread,
Aug 26, 2010, 6:28:05 AM8/26/10
to
On Aug 25, 9:03 pm, Öö Tiib <oot...@hot.ee> wrote:
> On 25 aug, 10:35, Goran Pusic <gor...@cse-semaphore.com> wrote:

[...]


> I don't understand that "assert(0)" part. It reads like
> "abort()" for me and "return" after it seems unreachable code.

Typically, with assert(0) you'll get an error message with the
line number and filename where the assert occurred. And the
return after it isn't unreachable if the code is compiled with
NDEBUG defined. (Not generally a good idea, but sometimes you
can't avoid it.)

> [...]

> > > If you have an OS that overcommits memory, you very likely
> > > won't get a bad_alloc anyway.

> > Yes. BTW, I hate overcommit, because large swaths of people have
> > experienced it and now think that handling memory correctly is
> > effectively futile. But that's not how C, C++, nor many other a-
> > language, is meant to work, not at all.

> That overcommit is red herring since it can be turned off with some
> kernel parameter like "vm.overcommit_memory = 0". If an user refuses
> to turn it off and random apps he runs get killed randomly then it is
> his fault, why should you care.

Whether it can be turned off, and how, depends on the OS---Linux
isn't the only one which overcommits. And a lot of Linux boxes
are running in situations where there isn't really a qualified
sysadmin, who can be presumed to know about such things. What
is the value set to by default on the distribution DVDs?

--
James Kanze

Öö Tiib

unread,
Aug 26, 2010, 7:14:10 AM8/26/10
to
On Aug 26, 1:28 pm, James Kanze <james.ka...@gmail.com> wrote:
> On Aug 25, 9:03 pm, Öö Tiib <oot...@hot.ee> wrote:
>
> > On 25 aug, 10:35, Goran Pusic <gor...@cse-semaphore.com> wrote:
>
>     [...]
>
> > I don't understand that "assert(0)" part. It reads like
> > "abort()" for me and "return" after it seems unreachable code.
>
> Typically, with assert(0) you'll get an error message with the
> line number and filename where the assert occurred.  And the
> return after it isn't unreachable if the code is compiled with
> NDEBUG defined.  (Not generally a good idea, but sometimes you
> can't avoid it.)

Yes, then it makes sense.

> > [...]
> > > > If you have an OS that overcommits memory, you very likely
> > > > won't get a bad_alloc anyway.
> > > Yes. BTW, I hate overcommit, because large swaths of people have
> > > experienced it and now think that handling memory correctly is
> > > effectively futile. But that's not how C, C++, nor many other a-
> > > language, is meant to work, not at all.
> > That overcommit is red herring since it can be turned off with some
> > kernel parameter like "vm.overcommit_memory = 0". If an user refuses
> > to turn it off and random apps he runs get killed randomly then it is
> > his fault, why should you care.
>
> Whether it can be turned off, and how, depends on the OS---Linux
> isn't the only one which overcommits.  

Yes, but do you know one where it is on and can not be turned off?
Linux is most widely accessible OS that has overcommit so i gave it as
example. Imagining OS that has overcommit unavoidable i have to
overtake memoy management/allocation, take large chunk and fill with
random numbers to be sure it is mine. Using problematic platforms has
a cost.

> And a lot of Linux boxes
> are running in situations where there isn't really a qualified
> sysadmin, who can be presumed to know about such things.  What
> is the value set to by default on the distribution DVDs?

The ones i have some experience with had it set 0 by default. I have
quite limited experience with Linux so i do not know, but having it on
by default sounds like having some "run unreliably" setting turned on
by default.

Goran Pusic

unread,
Aug 26, 2010, 7:43:05 AM8/26/10
to
On Aug 26, 10:26 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> I am curious: if I use a function that communicates failure (or some other
> condition) via throwing, how can RAII or ScopeGuard help me to avoid a catch
> statement?

Well... I __guessed__ that OP who complained about try/catch had too
many of them (perhaps I was wrong), and that they were caused by the
following situations:

{
TYPE r = alloc(); // r holds a resource; we must free it at the
block end.
workworkwork(); might throw, or simply return prematurely
free(r);
}

so you'd do:

{
TYPE r = alloc();
try
{
workworkwork();
free(r);
}
catch(...)
{
free(r); // must be a no-throw operation.
throw;
}
}

This alone is ugly, now imagine that you have another (or more)
resources in that block.

So, if you use RAII (that is, have resource-wrapper class for TYPE),
or scope guard, try/catch-es like above all disappear (as well as
multiple calls to free).

The number of "other types" of try/catch statements in code is IMO
very, very small. And the bigger the code base, the smaller it is
(compared to said size).

Goran.

Daniel T.

unread,
Aug 26, 2010, 8:02:24 AM8/26/10
to
Goran Pusic <gor...@cse-semaphore.com> wrote:

> > Frankly, I agree with 嘱 Tiib. It has been my experience that if my


> > program threw an exception, any exception, I had to re-write it so
> > that it no longer threw the exception.
>
> Even if exceptions was due to network failure that prevented a file
> from being open? No, that's too harsh.

If we were attempting to open a file, then it was absolutely necessary
for program continuance. Failure meant the program was broken.

> That said, I agree that there are situations where you'd say "well,
> this ate resources and it needs to be rewritten".
>
> > If the code's result is required for proper program functioning, and
> > it fails (throws an exception,) then the code has to be re-written
> > so that it won't fail anymore. If the code's result isn't required,
> > then why call the code in the first place?
>
> (I'll restrict my discussion to OOM conditions).
>
> Approach you're advocating works only where you can, through external
> means, guarantee that you'll have enough memory for whatever you want
> to do. I'd say that reduces your set of runtime environments.
>
> But in general, that's a tough call. Who's to prevent users from
> running the code on a system with less memory? Who's to prevent the
> administrator to reduce working set of the process? Who's to prevent
> the user to use virtual memory up to the full? Etc.

True. In the shop I'm talking about, our programs were all on game
consoles. We had a lot of guarantees like the ones you are wondering
about.

Vladimir Jovic

unread,
Aug 26, 2010, 8:31:10 AM8/26/10
to
Goran Pusic wrote:
>> Frankly, I agree with 嘱 Tiib. It has been my experience that if my

>> program threw an exception, any exception, I had to re-write it so that
>> it no longer threw the exception.
>
> Even if exceptions was due to network failure that prevented a file
> from being open? No, that's too harsh. That said, I agree that there
> are situations where you'd say "well, this ate resources and it needs
> to be rewritten".
>

You can terminate the application, pop the information box and wait, or
do something else. But you will not continue the execution like nothing
happened. What else can you do if required conditions are not met?

>> If the code's result is required for proper program functioning, and it
>> fails (throws an exception,) then the code has to be re-written so that
>> it won't fail anymore. If the code's result isn't required, then why
>> call the code in the first place?
>
> (I'll restrict my discussion to OOM conditions).
>
> Approach you're advocating works only where you can, through external
> means, guarantee that you'll have enough memory for whatever you want
> to do. I'd say that reduces your set of runtime environments.
>
> But in general, that's a tough call. Who's to prevent users from
> running the code on a system with less memory? Who's to prevent the
> administrator to reduce working set of the process? Who's to prevent
> the user to use virtual memory up to the full? Etc. What I spoke about
> (clean-up, get out, continue with something else) applies in all these
> cases.
>
> In general, there's too many factors out of your control. In my view
> if bad things __can__ happen, they __will__ (I am old :-) ). So your
> "there will be memory" approach does not fly all that well for me.

Can't beat Murphy's law.

If the program is for an embedded system (where everything is set), then
running out of memory can be solved only in two ways :
1) add more memory
2) see if you can reduce memory usage, but that is usually hard

btw every commercial software has minimal and recommended requirements.
If you fail to satisfy them - too bad, it will not run.

RB

unread,
Aug 26, 2010, 8:49:11 AM8/26/10
to

>Daniel T. wrote

> If we were attempting to open a file, then it was absolutely necessary
> for program continuance. Failure meant the program was broken.

( Please forgive me for even jumping in this thread, I don't mean to be
intrusive, especially since both of you are far above my level of programming
ability. But what the hell, I can learn only so much by sitting quietly at the
sidelines.)
But specifically "if it was absolutely necessary for this one file" well yes in
that one scenario it would mean continuing was futile but it would not in all cases
mean the app was broken, but rather the file format or pathname was broken or
corrupted. However "many" applications are written that utilize more than
"one" file. And you wouldn't want to shut down the app from underneath the
user in that case without giving them the option of "opening a different file" or
additionally utilizing the exception vehicle for backing out and resetting a filename
back to "untitled" so the user doesn't inadvertently overwrite the traversed set
filename that is current. At least I would not. Even if the file was the wrong format
or even corrupt it might have important data that could be salvaged in a dump and
the user would not want to inadvertently overwrite it next time they chose file save
not realizing it was still set to the old traversed filename This is something Goran
saved me from my ignorance on some time back.
Admittedly there are cases for sure that a shut down with hopefully a snapshot
report are in order, but not usually for opening a file or a network access failure.
In summation both of you have honed this subject done to many illuminating
pro's and con's of the aspect and I have enjoyed following it along.

Goran Pusic

unread,
Aug 26, 2010, 9:08:28 AM8/26/10
to
On Aug 26, 2:02 pm, "Daniel T." <danie...@earthlink.net> wrote:
> Goran Pusic <gor...@cse-semaphore.com> wrote:
> > > Frankly, I agree with Öö Tiib. It has been my experience that if my

> > > program threw an exception, any exception, I had to re-write it so
> > > that it no longer threw the exception.
>
> > Even if exceptions was due to network failure that prevented a file
> > from being open? No, that's too harsh.
>
> If we were attempting to open a file, then it was absolutely necessary
> for program continuance. Failure meant the program was broken.

So, you were signaling "program bug" failure using exceptions? That's
__not__ what you use exceptions for.

(Exceptions are __not__ a means of handling bugs in code, or at least
not a general-purpose one; e.g. there's no way to "handle" UB with
exceptions, not in any general sense of the world).

Goran.

RB

unread,
Aug 26, 2010, 9:23:17 AM8/26/10
to

> Goran Pusic

> So, you were signaling "program bug" failure using exceptions? That's
> __not__ what you use exceptions for.
> ( Exceptions are __not__ a means of handling bugs in code, or at least

> not a general-purpose one; e.g. there's no way to "handle" UB with
> exceptions, not in any general sense of the world ).
> Goran.

Well wait minute, Master, if I may, I can rationalize what you are saying
to a point ( I know you and Joe and are pretty much the same on this )
but there are times that "testers" are not going to catch every single bug. I
have a co worker in my cad department and her husband is a programmer
for medical software. I have heard that projects go out the door in some
scenarios (due to various deadline, economic or otherwise pressures) and
they sometimes know there are bound to be some bugs still in the code. (yea
that sounds scary I know for medical, but that's life on planet earth) Wouldn't
it be prudent to have exception frames to at least cover a crash report so it
could be rectified down the road ?
Or did I miss your context all together again ?

Goran Pusic

unread,
Aug 26, 2010, 10:00:54 AM8/26/10
to
On Aug 26, 3:23 pm, "RB" <NoMail@NoSpam> wrote:
> > Goran Pusic
> > So, you were signaling "program bug" failure using exceptions? That's
> > __not__ what you use exceptions for.
> > ( Exceptions are __not__ a means of handling bugs in code, or at least
> > not a general-purpose one; e.g. there's no way to "handle" UB with
> > exceptions, not in any general sense of the world ).
> > Goran.
>
> I have a co worker in my cad department and her husband is a programmer
> for medical software. I have heard that projects go out the door in some
> scenarios (due to various deadline, economic or otherwise pressures) and
> they sometimes know there are bound to be some bugs still in the code. (yea
> that sounds scary I know for medical, but that's life on planet earth) Wouldn't
> it be prudent to have exception frames to at least cover a crash report so it
> could be rectified down the road ?

I am not sure what you mean by "exception frames", not unless if you
think about details of implementation of exceptions for some platform
(which you seem to have done here before), but I guess you mean
something like "let's have an exception if code hits a bug".

If so, yes, perhaps, but that has very limited use. E.g. if your code
invokes undefined behavior (e.g. it overflows a buffer), any attempt
at signaling anything might with an exception might be futile. In my
experience, once UB happened, code is dead in the water. Even if code
ran for hours after.

But if e.g. code stumbles on a NULL pointer where there should be
none, it could throw e.g. a runtime_error with no harm. That case, a
case of precondition violation, if you will, could work, provided that
it's checked in every place it could have any influence on correct
operation. If not...

So... I agree that testing will never catch all bugs, but attempting
to catch them at runtime IMO does not help. IMO, if a bug (especially
UB) appears, I am lucky to crash as quickly as possible. And as you
might remember, to me, a crash != exception, not in C++ sense.

Goran.

RB

unread,
Aug 26, 2010, 12:07:35 PM8/26/10
to

> > RB

> > Wouldn't it be prudent to have exception frames to at least cover a
> > crash report so it could be rectified down the road ?

> Goran Pusic"


> I am not sure what you mean by "exception frames", not unless if you
> think about details of implementation of exceptions for some platform
> (which you seem to have done here before), but I guess you mean
> something like "let's have an exception if code hits a bug".

> But if e.g. code stumbles on a NULL pointer where there should be
> none, it could throw e.g. a runtime_error with no harm. ....< cut >
> ... could work, provided that it's checked in every place it could have
> any influence on correct operation. ........< > .........

> So... I agree that testing will never catch all bugs, but attempting

> to catch them at runtime IMO does not help..................< >

> And as you might remember, to me, a crash != exception,
> not in C++ sense.

Oh well, sorry for ambuity, I don't necessarily mean use exceptions for error
checking (persay, though sometimes that statement in some areas to me seems
to denote splitting hairs). But (in addition to previous said issues that occur
outside the realm of a bug) I was referring to (as you replied ) where the math
ceilings, floors or zero values were not covered like they should have been.
Say it's in a value realm that does not normally traverse and is somehow not
caught during testing.
Or an illegal address ptr access turns up. Now granted this is a error on the part
of a programmer (am I wrong ? ) since I have coded my own dummy self many
times to protect against ptr address areas (that change address during runtime)
from coming up illegal or even outside the stack. But I would think one would want
to have all the information they can reported back so as to solve their foo bar before
they become unemployed ? Even if you had a near omnipotent handler code in place
to allow for continued execution by resetting the context of the voilating address,
I would think you would still want to know about it.
Specifically some sort of base paradigm (third party) or maybe some simple
thing in like,

// in header file
// ( below type in winbase.h )
static LPTOP_LEVEL_EXCEPTION_FILTER m_prevFilter;

// in cpp file
CMissedSomething :: CMissedSomething( ) // Constructor
{ // Install SEH unhandled exception filter function
m_prevFilter = SetUnhandledExceptionFilter(MyUnCaughtFilter);
.............
// Check some stuff
..........
// send the context and whatever else needed to file and or email and
// hope to God our robotic heart surgery software hasn't killed someone
// before we get this dump.
}

Covering ( reporting an uncaught SEH exception ) the entire app. Obviously this
base setup could not handle inner exception area correction or object destruction
and heap deletetions (without adding inner C++ E frames in said areas ). And
admittedly even this could not catch all errors (that did not cause an SEH exception)
but to me this seems like a step in the right direction. But even say the omnipotent
handler could also call the into a report class (separate from MyUnCaughtFilter) and
still issue a report even if execution continues by resetting the illegal access context to
a legal address ( if said legal reset doesn't cause bad data down the road ).
Again "all" exceptions whether Hardware (divide / 0, etc) or software (RaiseException)
are implemented through the same base understructure. The C++ compiler uses this
same understructure while extending it's capability, albeit it does not attempt to cover
ascyncronous (SEH ) tracking. But once you get past the unwinding and object
destruction differences it all comes down to a raised exception.
Anyhow just my view looking out from my learning portal and listening to the pros.
No need to reply if I am too ambiguous but thanks for the thread because it has helped
me conceptualize what I have been studing for awhile.
Oh and by the way I bought the Exceptional C++ you mentioned. I went to Amazon
and got it used for $14 bucks. Can't beat that.
My compiler won't acknowledge exception specifications so I could not disassemble
it to see what it was doing. But after reading the online text of Sutter I was able to see
that when an exception specification says it won't throw anything, it is actually lying.
Rather the truth is the compiler (if it acknowledges said spec) puts in the catch blocks
for you and many times you actually end up with more try catches than if you had typed
them yourself while deciphering where you needed them. Most compilers have
disregarded this specification.

James Kanze

unread,
Aug 26, 2010, 12:39:53 PM8/26/10
to

An assertion failure will, or should, generate all of the
necessary information for debugging. That's why systems provide
different means of terminating a program. When you find a bug
in the code, however, you should terminate the program as
quickly as possible, doing as little extra work as possible.
Partially, in fact, to ensure that the information about the
crash does correspond to the actual context where the crash
occured. In the case of critical systems, to get out of the way
so the backups can take over. And in all cases, because if the
program is corrupt, who knows what it will do when unwinding the
stack.

--
James Kanze

James Kanze

unread,
Aug 26, 2010, 12:51:49 PM8/26/10
to
On Aug 26, 12:14 pm, Öö Tiib <oot...@hot.ee> wrote:
> On Aug 26, 1:28 pm, James Kanze <james.ka...@gmail.com> wrote:

[...]


> > > That overcommit is red herring since it can be turned off
> > > with some kernel parameter like "vm.overcommit_memory
> > > = 0". If an user refuses to turn it off and random apps he
> > > runs get killed randomly then it is his fault, why should
> > > you care.

> > Whether it can be turned off, and how, depends on the
> > OS---Linux isn't the only one which overcommits.

> Yes, but do you know one where it is on and can not be turned
> off?

I've known some in the past. (At least one has evolved to make
overcommit optional, turned off by default. And I think it can
be turned on at a process by process level, which is
a reasonable option.)

> Linux is most widely accessible OS that has overcommit so
> i gave it as example. Imagining OS that has overcommit
> unavoidable i have to overtake memoy management/allocation,
> take large chunk and fill with random numbers to be sure it is
> mine. Using problematic platforms has a cost.

Yes. Where I was working at the time, our solution was to not
use them:-). Anytime you're doing something serious, which has
to work, then you cannot permit overcommit.

> > And a lot of Linux boxes are running in situations where
> > there isn't really a qualified sysadmin, who can be presumed
> > to know about such things. What is the value set to by
> > default on the distribution DVDs?

> The ones i have some experience with had it set 0 by default.
> I have quite limited experience with Linux so i do not know,
> but having it on by default sounds like having some "run
> unreliably" setting turned on by default.

If vm.overcommit_memory == 0, Linux uses "heuristic overcommit
handling", whatever that means (but it does mean
overcommitting). 1 means always overcommit, and 2 means don't
overcommit. If vm_.overcommit_memory is anything but 2, your
system is unreliable. (On the other hand, you may be able to do
more with it if it doesn't crash. Some programs do allocate
large blocks of memory that they don't fully use.)

--
James Kanze

Kai-Uwe Bux

unread,
Aug 26, 2010, 1:59:14 PM8/26/10
to
Goran Pusic wrote:

I see, you worry about the catch block that is not concerned with actually
dealing with the exception thrown by workworkwork(). That's why you rethrow.
You still need to catch the exception from workworkwork() and handle it
proper. What RAII gives you is automatic resource management during stack
unwinding.

> The number of "other types" of try/catch statements in code is IMO
> very, very small. And the bigger the code base, the smaller it is
> (compared to said size).

Hm, I am not so sure about that. It very much depends on how religiously and
locally you handle exceptions. On one extreme end, you let everything
propagate to the top-level and have one catch-all block. On the other end of
the spectrum, you can handle each exception as early as possible. In the
later case, you will still have a sizable number of catch blocks.


Best

Kai-Uwe Bux

joe

unread,
Aug 26, 2010, 2:26:19 PM8/26/10
to

(I tried to be brief below, surely at the expense of being entirely
"correct". I started writing a paper once on the topic, but never pursued
it to the end and have it reviewed and published. Surely what is below is
muchly the same as some of the topics in the paper, albeit just thoughts
off the top of my head at this time in reply to the topic at hand in this
thread and in reply to the post above).

Two things first. Errors and bugs are different animals. Exceptions (or
return codes or ...) can help you manage the former, but not the latter.
Assertions help with the latter, but not the former. Errors are dealt
with in released software and are expected. Bugs are (attempted to be)
removed during development time and are "unexpected" in released
software. Many errors can be "fixed up" during running and indeed that is
what error "handling" is all about: thinking about all the possibilities
and doing contingency planning. I don't have any example of bugs being
fixed up on-the-fly in a running program.

That said, the assumption that there can be "an all powerful exception
handler" that can catch anything (errors, bugs) you failed to address in
your code, is erroneous. Realize that if there was nothing to raise an
exception in the first place, then you can't handle it, so you won't be
able to handle that null ptr that you didn't assert on during development
of the software (maybe an OS will "have the final say" about it). The
program is going to crash. If that kind of thing cannot be tolerated,
then you have to use something out-of-band (OOB) (to hijaack a term from
the comm world). Redundancy (in software or hardware or complete systems)
is just one technique of fault tolerance. Not every system or program
needs that level of fault tolerance.

What is appropriate depends on the application and type of
program/system. Consider how a desktop application program may fault and
produce a messagebox to the user indicating that the program WILL
terminate (maybe it will save your work, maybe it won't or maybe it has
been saving it all along) and offer to send a bug report to the developer
so they can release a patch to fix the bug. The generated messagebox was
the result of an assertion failure. Had the assertion not been there and
retargeted in release mode, the program would have crashed, and programs
do crash and in a desktop program the OS would have saved the rest of the
system from failing.

So, there is no "easy answer/silver bullet" in regards to error
"handling" strategy and tactics. "Strategy" is the big picture (What kind
of software program is it? What level of fault tolerance is required?
What will be tolerated by users?) whereas "tactics" are the details and
localized stuff (Should I return an error code from this function or
raise an exception? Should errors be logged? Is a messagebox OK? Should
an administrator be notified?). There is a lot to thing about while
writing software and up front planning is required. In order to do that
up front planning, though, one has to be well-versed in the principles
and techniques.


RB

unread,
Aug 26, 2010, 3:14:35 PM8/26/10
to

> Kai-Uwe Bux wrote

> I see, you worry about the catch block that is not concerned with actually
> dealing with the exception thrown by workworkwork(). That's why you rethrow.
> You still need to catch the exception from workworkwork() and handle it
> proper. What RAII gives you is automatic resource management during stack
> unwinding.

Please excuse if I may also reply. I am just now studying RAII and have not
gone into the depth with it as I have with the exception mechanism. But it appears
that what you are saying is that, granted he would not have to worry about the
> > catch(...)
> > {
> > free(r);
since the wrapped resoures in the RAII class object would go out of scope
(be destructed ) when the calling function finished. I get that part, so then
your are further saying that " if " there are other ramifications involved other
than freeing resources and destructing objects he would have to handle the
exception. Well yes I agree and Goran must have been focusing on the
resource freeing only in this scenario since I know he is well aware of such
other ramifications since he was the first to point them out to me some time
back in the area of file access and exceptions.
Possibly the ScopeGuard ( third party ? ) helps in this area. Anyhow in his
time zone it will be some hours before we can get a reply on that.



> On one extreme end, you let everything propagate to the top-level and have
> one catch-all block. On the other end of the spectrum, you can handle each
> exception as early as possible. In the later case, you will still have a sizable
> number of catch blocks.

Is there one rule for this ? It would appear to me that one would want to
place try / catch blocks in the function that holds objects you want destructed
in case of an exception ( if you were not implementing RAII ) and otherwise
at a position that would be at a point where code that would rectify "other
ramifications " ( besides resource management ) could execute prior to
other continuing code?
Please point out the any concept I have missed in that assumption.
And again I totally agree with the concept that " if " no exception blocks are
necessary (for varied reasons) then none should be there. Exception blocks
should never be used casually to replace all error checking and/or handling.
Of course this whole thread has been about the gray area in between.

RB

unread,
Aug 26, 2010, 3:31:52 PM8/26/10
to

> joe wrote

> (I tried to be brief below, surely at the expense of being entirely
> "correct". ............ <cut >..................................

> Two things first. Errors and bugs are different animals. Exceptions (or
> return codes or ...) can help you manage the former, but not the latter.
> Assertions help with the latter, but not the former. ........< >............

> So, there is no "easy answer/silver bullet" in regards to error
> "handling" strategy and tactics. "Strategy" is the big picture (What kind
> of software program is it? What level of fault tolerance is required?
> What will be tolerated by users?) ...........< >.................

Thanks joe
And by the way in my posted statement of

>> ( I know you and Joe and are pretty much the same on this )

I was referring to Joseph Newcomer not you. But none the less I thank
you for the very informative and detailed reply. I read it over and thoroughly.
I have only one question. Could you give me a brief (if possible) description
of what a Bug is, since I now know it is not an error.

joe

unread,
Aug 26, 2010, 3:45:56 PM8/26/10
to
Goran Pusic wrote:

> Well, I am not so sure about that. To me, exceptions are a way to
> __structure code in face of unexpected situations__.

"exception handling" = "error handling". There is no difference when used
like that. Exceptions are C++ machinery to assist in "error handling".
The kinds of errors that machinery was designed for are definitely
EXPECTED.

>They are not
> there to "handle errors",

Yes they are, that is the intent: to keep a program running and only
bugout as a last resort.

> and they are certainly not there to somehow
> handle __coding errors__ (that's IMO a massive error many people
> make).

Right, debugging is a separate area of concern in software development.

>
> And indeed, if you look at your OS, it does __not__ emit any
> exceptions in C++ sense (nor in any other language sense, really). Not
> even Windows does that. When you receive windows exception (SE one),
> your code is already dead.
>

Asynchronous errors?

> Effectively, exceptions help you to eliminate a myriad of error code
> paths and transport error info to a place where you can do something
> about that error. No more, no less.

I tend to view the whole schmere of the C++ exception machinery as a
propagation technique only also. But, whatever propagation technique is
used, the goal is (should be) handling of the errors. Of course one must
identify the errors first, so maybe you are just thinking about a subset
of them.

> In a way, when speaking about
> exceptions, I often say "forget error __handling__, there is no such
> thing". Because, what we call error handling, exceptions or not, is
> almost always "clean up and get out, report error to some external
> factor".

"Clean up and get out" sounds like being lazy with the handling thinking.
Thinking about handling errors will necessarily flesh-out an otherwise
skeletal piece of software, read, affect it's design. "Clean up and get
out" as the predominant strategy is closer to assertion-checking than EH,
IMO.

> It's _resource handling_ (and sometimes, program state
> handling), on one hand, and _error reporting_, on the other. 'cause,
> situations where error happens and code can correct it, are __rare__.

Perhaps you are focusing just on the errors that WILL result in
termination and not thinking about all the other errors that can happen
and can and should be handled successfully without termination?

> And that's the ultimate reason why exceptions are so good - they help,
> massively, in handling common situation where, upon error, all you can
> do is to clean up and get out.

Or, perhaps you are focusing just on those errors that will likely
propagate across multiple levels? I don't distinguish between
"exceptions" and "errors", that's just terminology that means the same
thing IMO.

joe

unread,
Aug 26, 2010, 3:51:17 PM8/26/10
to
RB wrote:
>>> "exception specifications"...................
>
>> I suggest you take a look at what Herb Sutter has to say on exception
>> spec (basically: they way they are defined by C++, are useless :-) ).
>> (Search gotw.ca for "throw()" ). His explanation is much better than
>> anything I can come up here. :-)
>
> Thanks will do that soon.
>
>>> 3. It would appear that exceptions are a reality that hardware and
>>> OS engineers deemed necessary .......................

>
>> Well, I am not so sure about that. To me, exceptions are a way to
>> __structure code in face of unexpected situations__. They are not
>> there to "handle errors", and they are certainly not there to somehow

>> handle __coding errors__ (that's IMO a massive error many people
>> make).
>
> Well I totally agree with your above sumation, BUT what I was
> attempting to say was "all " of the exception ability (even c++ ) is
> created
> (albeit expanded) on top of the basic provided by the hardware
> interrupt system and OS

Not at all. Those are asynchronous/OOB errors and the C++ machinery is
not designed to interact with that.

> partnership of the linked list of handlers at FS:[0]. That said I was
> stating the
> "origin" of said capability was (as I see it ) the promotion of a
> more stable computer product (or least an informed exit ) as opposed
> to an unlabeled crash.


>> And indeed, if you look at your OS, it does __not__ emit any
>> exceptions in C++ sense (nor in any other language sense, really).
>> Not even Windows does that. When you receive windows exception (SE
>> one), your code is already dead.
>

> Well no I must have been ambiguous, since I did not mean that the OS
> would implement an exception frame that would comply with the trylevel
> and
> scopetables of the C compiler's SEH

SEH is a Microsoft thing that is orthogonal to C++ exceptions.


joe

unread,
Aug 26, 2010, 4:13:12 PM8/26/10
to
RB wrote:
>> joe wrote
>> (I tried to be brief below, surely at the expense of being entirely
>> "correct". ............ <cut >..................................
>> Two things first. Errors and bugs are different animals. Exceptions
>> (or return codes or ...) can help you manage the former, but not the
>> latter. Assertions help with the latter, but not the former.
>> ........< >............ So, there is no "easy answer/silver bullet"
>> in regards to error "handling" strategy and tactics. "Strategy" is
>> the big picture (What kind of software program is it? What level of
>> fault tolerance is required? What will be tolerated by users?)
>> ...........< >.................
>
> Thanks joe
> And by the way in my posted statement of
>>> ( I know you and Joe and are pretty much the same on this )
> I was referring to Joseph Newcomer not you.

I know that, silly.

> But none the less I thank
> you for the very informative and detailed reply. I read it over and
> thoroughly. I have only one question. Could you give me a brief (if
> possible) description of what a Bug is, since I now know it is not an
> error.

Are you trolling? Anyway, Google it and Wikipedia it for all the details.
You'll find that the first one was actually a moth and hence the term
"bug".


RB

unread,
Aug 26, 2010, 8:47:06 PM8/26/10
to

>> RB previously wrote:
>> Well I totally agree with your above sumation, BUT what I was
>> attempting to say was "all " of the exception ability (even c++ ) is
>> created (albeit expanded) on top of the basic provided by the
>> hardware interrupt system and OS

> joe wrote


> Not at all. Those are asynchronous/OOB errors and the C++ machinery
> is not designed to interact with that.

> SEH is a Microsoft thing that is orthogonal to C++ exceptions.

Well apologize again if I was ambiguous, but I did not say that C++
(trylevel only, syncronous) exception frames were designed to work (persay)
with SEH (trylevel and scopetables asyncronous).
Again to try and make it clearer, " all " exception mechanisms in a
MS VS windows app (with the exception possibly of NET JIT code, I
don't know about that ) run on ( but expands beyond ) the basic Frame
handler chain found at FS:[0] . Granted the compiler adds much more
unwind and trylevel code but it all functions on top of the basic chained
system of installed handler frames at FS:[0]
You can have both in the C++ exceptions and SEH exceptions in the same
program but the compiler won't let you have both in the same function.
In fact every windows app (mfc included ) has an SEH _try and _except
in the WinMainCRTStartup( ) code to cover the call to your compiler's
winmain (or console main ) function. This covers the whole windows app
for any SEH exception if not handled by your app's code. This CRT startup
function is where the final handler ( the Unhandled Exception dialog
with an option to send to MS ) kicks in " if " you have not handled it before
it gets to there. If you have not handled it with a specific C++ ,
catch( DivideByZero& E ) or a catch(...) or an SEH _except or with
SetUnhandledExceptionFilter( YourCustomFilter);
This CRT startup is in every MS VS windows app whether you use
C++ try catch or not or use both SEH in one function and C++ another.

Here the difference in stack frames
MS VC C++'s (try catch) Frame
ebp-C [ebp-C] [ebp-8] [ebp-4] [ebp-0] ebp-0
| PrevFrame|Handler | TryLevel |CallerEBP | FrameEBP
Frame-> [Frm +0] [Frm+4] [Frm+8h] [Frm+Ch] <-Frm+Ch

MS VC CRT's (SEH _try _except) Frame (also CRT final handler)
ebp-10 [ebp-10] [ebp-C] [ebp-8] [ebp-4] [ebp-0] ebp-0
PrevFrame | Handler|ScopeTable|TryLevel|CallerEBP|FrameEBP
Framer->[Frm+0] [Frm+4] [Frm+8h] [Frm+Ch] [Frm+10h]<-Frm+10h
Scopetable[0] PrevTryLevel: @ FFFFFFFF (always preceeds a trylevel 0)
CRTFilterFunc: @ 00401CA8 (depends on compile)
CRT__except block: @ 00401CC3 (depends on compile)

Win32 OS system final Handler's Frame (the basic frame) covers all processes
started and will surface when say an assembler program with no CRT startup
has an exception.
| PrevFrame|Handler |
Framer->[ Frm+0] [ Frm+4]

If a compiler (or you if you write your own custom handler) wants to do
exceptions on win32 it must play by the frame rules since when an exception
occurs the system walks the chain and calls each (and every handler ) up until
a handler is found that will handle the exception, when that is found based on
it's return, the system then calls each frame again ( if it is on the stack below
the frame that agreed to handle the E ) with the flag set to unwind.
--------------------------------
// pasted right out of my version of CRT0.C //
wWinMainCRTStartup()
{
/*
* Guard the remainder of the initialization code and the call
* to user's main, or WinMain, function in a __try/__except
* statement.
*/
__try
{
......
......
exit(mainret); // you will come here if normal exit OR you
// handled any exception but still exited.
}
// This is CRTs final handler frame, here if exception not handled.
__except ( _XcptFilter(GetExceptionCode(), GetExceptionInformation()) )
{
/*
* Should never reach here
*/
_exit( GetExceptionCode() );
} /* end of try - except */
}

RB

unread,
Aug 26, 2010, 8:53:34 PM8/26/10
to

>> I was referring to Joseph Newcomer not you.

> I know that, silly.

Oh well excuse me.


>> But none the less I thank
>> you for the very informative and detailed reply. I read it over and
>> thoroughly. I have only one question. Could you give me a brief (if
>> possible) description of what a Bug is, since I now know it is not an
>> error.

> Are you trolling?

No I'm not trolling, I guess I am just that stupid. But never mind I don't need
input from such an ass.

RB

unread,
Aug 26, 2010, 9:16:52 PM8/26/10
to
I looked up the meaning of trolling,
" In Internet slang, a troll is someone who posts inflammatory,
extraneous, or off-topic messages in an online community"
I did not know what it meant previously. In any case I certainly
was not trying to troll. The only thing I am guilty of is being
somewhat stupid in some areas. Possibly I over reacted to your
"silly" etc. on my post above. Who knows, I know you probably
don't care. That's all. Sorry for any wrong doing on my part.

RB

unread,
Aug 26, 2010, 9:35:16 PM8/26/10
to
Found the answser to my error bug question.
Error: Is an undesirable deviation from requirements or Cosmetic .

Bug: Is an error found BEFORE the application goes into production or missing Functionality.

Defect :Is an error found AFTER the application goes into production or missing Requirement

Daniel T.

unread,
Aug 26, 2010, 11:44:51 PM8/26/10
to
Goran Pusic <gor...@cse-semaphore.com> wrote:
> "Daniel T." <danie...@earthlink.net> wrote:
> > Goran Pusic <gor...@cse-semaphore.com> wrote:
> > > "Daniel T." <danie...@earthlink.net> wrote:
> > >
> > > > Frankly, I agree with Öö Tiib. It has been my experience that if
> > > > my program threw an exception, any exception, I had to re-write
> > > > it so that it no longer threw the exception.
> > >
> > > Even if exceptions was due to network failure that prevented a
> > > file from being open? No, that's too harsh.
> >
> > If we were attempting to open a file, then it was absolutely
> > necessary for program continuance. Failure meant the program was
> > broken.
>
> So, you were signaling "program bug" failure using exceptions?

Remember the subject of this thread... We weren't using exceptions at
all. Some people seem to think that one can't use the standard library
without exceptions, but we did by simply converting the throws into
assertion failures; by treating the situations where exceptions are
thrown in the library as precondition violations.

Daniel T.

unread,
Aug 27, 2010, 12:08:45 AM8/27/10
to
"RB" <NoMail@NoSpam> wrote:
> Daniel T. wrote
>
> > If we were attempting to open a file, then it was absolutely
> > necessary for program continuance. Failure meant the program was
> > broken.
>
> (Please forgive me for even jumping in this thread, I don't mean to be

> intrusive, especially since both of you are far above my level of
> programming ability. But what the hell, I can learn only so much by
> sitting quietly at the sidelines.)

By all means, join in! One of the major aids for me in learning how to
program is attempting to answer questions in this group. Also, I would
sometimes take a stand on a controversial subject here and then see if I
can defend it. That helped me greatly.

> But specifically "if it was absolutely necessary for this one file"
> well yes in that one scenario it would mean continuing was futile but
> it would not in all cases mean the app was broken, but rather the file
> format or pathname was broken or corrupted.

Here's where domain matters. If opening the file wasn't absolutely
necessary, I wouldn't even be trying to open it. We never did anything
that wasn't absolutely necessary. To put it another way, we never did
anything that could fail.

> In summation both of you have honed this subject done to many
> illuminating pro's and con's of the aspect and I have enjoyed
> following it along.

I'm glad to hear it. Here is something interesting for you to study.
Take a look at all the possible exceptions that the standard library can
throw and why it would throw them (it shouldn't take too long, there are
only 8 of them.) Now for each one, ask yourself, "if this exception
threw during some run of my program, under what circumstances would I
write a catch to handle the exception and continue running the program,
under what circumstances would I re-write the code so I knew the
exception wouldn't throw again, under what circumstances would I use the
exception as a reason to exit the application?

I think you will find the results surprising. I would love to hear what
you learned from such an exorcise, email me if you want
(dani...@earthlink.net). If you choose to post on the group, email me
and let me know what the subject is so I can keep an eye out for it.

joe

unread,
Aug 27, 2010, 1:19:45 AM8/27/10
to

I don't agree with those definitions, and they seem a bit "lofty".
"bug/defect", "tomato/tomoto", they mean the same thing to me. That one
tries to get all the bugs out before release doesn't factor into the
definition for me, nor does it make me want multiple terms based upon the
discovery time of the bug.

In C++, "errors" are expected and defined things (though probably occur
rarely) that one can manage with the exception machinery (or some other
facilities, perhaps that which one built themself). Errors are detectable
while bugs are not (but they can be flushed out by testing and reduced
via good coding practices). Robustness against errors is designed into a
program whereas robustness against bugs cannot be (bug-reducing practices
and processes are effective means though and OOB techniques are available
if required). Errors are thought about proactively while (specific) bugs
can only be thought about retroactively. The process after error is
defined and controlled whereas with a bug, the behavior is undefined.

So, what is a bug? A moth, of course. Therefor, always put a mothball in
with any shrinkwrapped software you ship.


joe

unread,
Aug 27, 2010, 1:53:57 AM8/27/10
to
RB wrote:
> I looked up the meaning of trolling,
> " In Internet slang, a troll is someone who posts inflammatory,
> extraneous, or off-topic messages in an online community"

Well that's a definition I don't/won't use. Feigning not knowing
something to test someone else would be an example of trolling by my
definition. Another example would be purposely asking vague or
provocative questions just to instigate a flamewar. If the purpose is to
enrage or create chaos/commotion, then that would be trolling. If the
purpose is to obtain or convey on-topic information, I would not call it
trolling. (A more "modern" definition may note that not all trolling is
necessarily bad). Your definition seems more akin to public drunkeness.

> I did not know what it meant previously.

Apparently, the "definitions" of it are all over the map rather than on
the same page.

> In any case I certainly
> was not trying to troll. The only thing I am guilty of is being
> somewhat stupid in some areas. Possibly I over reacted to your
> "silly" etc. on my post above.

I said "silly" because I would be quite aware of someone who I have gone
back-n-forth in detail about error handling and I'd expect you to know
that I would not think that someone else being referred to was actually a
reference to me, silly. ;)


Goran Pusic

unread,
Aug 27, 2010, 2:42:58 AM8/27/10
to
On Aug 26, 7:59 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> > The number of "other types" of try/catch statements in code is IMO
> > very, very small. And the bigger the code base, the smaller it is
> > (compared to said size).
>
> Hm, I am not so sure about that. It very much depends on how religiously and
> locally you handle exceptions. On one extreme end, you let everything
> propagate to the top-level and have one catch-all block. On the other end of
> the spectrum, you can handle each exception as early as possible. In the
> later case, you will still have a sizable number of catch blocks.

My question to you is, why do you want to handle exceptions locally?
Give some examples, or better yet, don't, just look at your own code
and count try/catch-es ;-).

If you use RAII /scope guard, try/catches are of two sorts:

1. report the error and continue working (or, for top-level catch in
main, exit)
2. re-throw the error with additional info.

1. is extremely rare, for example, top-level try/catch in main or any
thread function, or, in a GUI event loop, on the said loop, or on
similar loops elsewhere, where your mode of operation is "loop
until....", and you dont' want to terminate a loop due to an error in
one iteration.

2. is more common, but depends on how precise you can be at the actual
throw site, and how much you want to add while unwinding the stack.

Goran.

w...@seed.net.tw

unread,
Aug 27, 2010, 3:54:41 AM8/27/10
to

std::vector<T> arr=initialize();
size_t i;
try {
for(i=0; i<arr.size()+1; ++i) {
if(arr.at(i)==T()) break;
}
}
catch(const std::out_of_range& e) {
assert(i>=arr.size()); // Can I really assure this assertion?
}
catch(const std::invalid_argument& e) {
// T::T(), T::operator==() and std::vector::at did not say they
// will throw this type. What will be the fate of this exception?
}

General guideline for throw site: "stack unwinding to exit".

Goran Pusic

unread,
Aug 27, 2010, 8:01:01 AM8/27/10
to
On Aug 27, 9:54 am, w...@seed.net.tw wrote:
> std::vector<T> arr=initialize();
> size_t i;
> try {
>   for(i=0; i<arr.size()+1; ++i) {
>     if(arr.at(i)==T()) break;
>   }}
>
> catch(const std::out_of_range& e) {
>   assert(i>=arr.size());   // Can I really assure this assertion?}

I am not sure why I was quoted for this snippet, nor what is the
purpose of it all, but here goes...

This code most certainly has a bug. It makes no sense whatsoever to
ever try to call at(v.size()).

Exceptions are __not__ means of handling bugs. A "catch" like the one
you made is an attempt at handling an exception, therefore, at
handling a bug. Therefore your catch is misplaced.

Exceptions __can__ be used to __report__ bugs, but they are often
suboptimal for that, too; if possible in the given runtime
environment, a crash and a dump is better, because that allows you to
see the exact place where problem happened, which, in case of a bug,
is important. If, however, you do want to use them to report bugs, you
should let them unwind the stack up to the end and terminate. You
__may__ do ^^^ on the way up the stack, though.

Catching the exception above, that is caused by a bug, is a __bad__
idea. Bugs should be fixed, not "handled". Unless code inside catch
can somehow change the "i<arr.size()+1" to something correct, it makes
no sense whatsoever to catch anything, except if the purpose is to
mask the bug and do something wrong anyway.

As for invalid_argument, I guess you wanted to hint at the possibility
that operator== could throw that. Well, invalid_argument, because
invalid_argument is, just like out_of_range, a logic_error, that is, a
bug. Same logic applies.

If, by any chance, you did something like:

// ^^^
catch(const logic_error& e)
{
string more("We have a bug. We caught it in " + string(__FILE__) +
", line " + string(__LINE__) + "error text was: "
+ string(e.what());
throw logic_error(more);
}

, that is, if you were in 2) of my exception classification ;-), your
catching would have some sense. The way it is now, everything you
wrote is one huge bug to me.

> General guideline for throw site:  "stack unwinding to exit".

I don't know what you mean by this, but I know that throw site can't
decide what will happen with the thrown exception. Next function can
catch it, so what gives?

Goran.

RB

unread,
Aug 27, 2010, 8:19:09 AM8/27/10
to

Well that makes sense. I apologize for letting my emotions take offense
to my own lack of awarness. But sometimes it is frustrating to try to
put down exactly what you are asking and still not have it misunderstood
by the person you are depending on for an answer.
I work in a different vocation that has long hours of detailed stuff that
most folks would find boring. But I love to program as a productive hobby
so to speak in that I have been able to progress to the point that I can
actually write routines that help me with mathematical logistics in my vocation.
Items that I used to have to do long hand on my calculator while holding
the whole scenario in my head, now I have routines that hold and track
all my data while they are computing so I don't forget where I started
or where I am.
But writing them "correctly" ah that is where all of you guys on the
newsgroups have helped me tremendously and I owe much to all of you.
RB

Goran Pusic

unread,
Aug 27, 2010, 8:32:13 AM8/27/10
to
On Aug 27, 2:19 pm, "RB" <NoMail@NoSpam> wrote:
>    I work in a different vocation that has long hours of detailed stuff that
> most folks would find boring. But I love to program as a productive hobby
> so to speak in that I have been able to progress to the point that I can
> actually write routines that help me with mathematical logistics in my vocation.
> Items that I used to have to do long hand on my calculator while holding
> the whole scenario in my head, now I have routines that hold and track
> all my data while they are computing so I don't forget where I started
> or where I am.

If you have a lot of maths, there's specialized software for that
(Mathematica, Matlab...) that easily beats C++ in ease of use?

Goran.

w...@seed.net.tw

unread,
Aug 27, 2010, 11:59:26 AM8/27/10
to
On 8月27日, 下午8時01分, Goran Pusic <gor...@cse-semaphore.com> wrote:
> On Aug 27, 9:54 am, w...@seed.net.tw wrote:
>
> > std::vector<T> arr=initialize();
> > size_t i;
> > try {
> >   for(i=0; i<arr.size()+1; ++i) {
> >     if(arr.at(i)==T()) break;
> >   }}
>
> > catch(const std::out_of_range& e) {
> >   assert(i>=arr.size());   // Can I really assure this assertion?}
>
> I am not sure why I was quoted for this snippet, nor what is the
> purpose of it all, but here goes...
>
Because I read your sorting 2, triggered my obsession that I wanted
to notify you that the caught object (especially if they are reused)
can mean differently, not as most people thought. Throw type for
dedicated purpose is fine, though. Slightly modified example to
clarify:

std::vector<T> arr(100);
size_t i=0;
try { arr.at(i); }
catch(const std::out_of_range&) {
assert(i>=arr.size()); // Time bomb! Can I really assure this
// assertion?

I remember I read from a book that C++ does not guarantee the proper
handling if the size of thrown object is larger than the standard
exception type. I am appropriate if anyone can point out a reference.
The above code is potential for bad_alloc.


>
> , that is, if you were in 2) of my exception classification ;-), your
> catching would have some sense. The way it is now, everything you
> wrote is one huge bug to me.
>
> > General guideline for throw site:  "stack unwinding to exit".
>
> I don't know what you mean by this, but I know that throw site can't
> decide what will happen with the thrown exception. Next function can
> catch it, so what gives?
>
> Goran.

Maybe just different terms for the same thing, not necessarily
against your opinion.

w...@seed.net.tw

unread,
Aug 27, 2010, 12:07:48 PM8/27/10
to

Correction. The example should be:

std::vector<T> arr(100);
size_t i=101;


try { arr.at(i); }
catch(const std::out_of_range&) {
assert(i>=arr.size()); // Time bomb! Can I really assure this

// assertion,
}

w...@seed.net.tw

unread,
Aug 27, 2010, 12:38:11 PM8/27/10
to
Really really apologize, the above is not correct.
It should be:

std::vector<T> arr=initialize();
size_t i;
try {

for(i=0; i<arr.size(); ++i) {


if(arr.at(i)==T()) break;
}
}
catch(const std::out_of_range& e) {

joe

unread,
Aug 27, 2010, 2:53:42 PM8/27/10
to
Goran Pusic wrote:

> Exceptions are __not__ means of handling bugs. A "catch" like the one
> you made is an attempt at handling an exception, therefore, at
> handling a bug. Therefore your catch is misplaced.
>
> Exceptions __can__ be used to __report__ bugs, but they are often
> suboptimal for that, too; if possible in the given runtime
> environment, a crash and a dump is better, because that allows you to
> see the exact place where problem happened, which, in case of a bug,
> is important. If, however, you do want to use them to report bugs, you
> should let them unwind the stack up to the end and terminate. You
> __may__ do ^^^ on the way up the stack, though.

Assertions ("bug catchers" if you will) can be mapped to exceptions for a
release build to facilitate reporting to the developer, for example.


Öö Tiib

unread,
Aug 27, 2010, 4:33:52 PM8/27/10
to

Heuristic sounds suspicious, perhaps that 2 is best then, thanks.

Ian Collins

unread,
Aug 27, 2010, 5:00:37 PM8/27/10
to

Unless the exception somehow preserves the context of the assertion, it
will be worse than useless.

--
Ian Collins

joe

unread,
Aug 27, 2010, 5:47:23 PM8/27/10
to

A programmer is free to make his exception classes as elaborate as he
wants to. Attach a stack trace, for example, if he wants to.


Ian Collins

unread,
Aug 27, 2010, 5:54:23 PM8/27/10
to

Which is what I said. But no matter how elaborate the exception is, if
the stack is munted, or memory is exhausted or <insert bad things here>
when it is thrown, it is still worse than useless.

--
Ian Collins

Kai-Uwe Bux

unread,
Aug 27, 2010, 6:16:37 PM8/27/10
to
Ian Collins wrote:

True, but not really relevant is this context, or is it? Here, the focus is
on exceptions that replace asserts. If your application suffers from a
corrupted stack, you are in UB land anyway and neither asserts nor
exceptions will handle that gracefully. Thus, I don't see how that says
anything on the alternative of reporting the manifestation of a bug via
asserts or exceptions.


Best

Kai-Uwe Bux

joe

unread,
Aug 27, 2010, 6:27:29 PM8/27/10
to

Asserts aren't going to be about OOM and such. Note that asserts catch
things before they go awry mostly, like null ptr args, else you wouldn't
use them for debugging in the first place. So whatever information the
developer has been receiving during development, he can still get from
released software if he wants to. Just because the attempt to report the
error may, in the rare case, fail doesn't mean you can't make a best
effort try to do so. It's of course, application-specific and
programmer-specific. I don't use exceptions that way, but surely some do,
and I may analyze doing so in the future.


Ian Collins

unread,
Aug 27, 2010, 6:43:07 PM8/27/10
to

Fair enough. A more realistic situation would be a method detecting its
object is in an inconsistent state. Throwing an exception would very
likely result in an attempt to destroy the object during stack
unwinding, causing more grief.

I for one much prefer a core file!

--
Ian Collins

Öö Tiib

unread,
Aug 27, 2010, 7:14:42 PM8/27/10
to

Depends on type of object and inconsistency. For example if external
device tells that value of some channel on it is 5 for what your
software has information that minimum value for it is 0 and maximum
value is 4. Is software broken? Is device broken? Has device been
upgraded without upgrading software? Maybe there was noise in
communication channel? It is highly likely that neither device maker
nor its operator expects the software to suicide right away in such a
situation.

Ian Collins

unread,
Aug 27, 2010, 7:47:10 PM8/27/10
to

True. But the discussion was about mapping assertions to exceptions
(which is still suicide) as a diagnostic tool. The situation you
describe probably wouldn't justify an assertion.

--
Ian Collins

Öö Tiib

unread,
Aug 27, 2010, 8:15:13 PM8/27/10
to
On 28 aug, 02:47, Ian Collins <ian-n...@hotmail.com> wrote:

Yes, but that is sort of too low level to decide what is good.
Assertion is usually about contract violation. For example my function
is described to not accept null pointer arguments, then it asserts
that argument is not null. If it was described to throw on null
pointers, then it throws when argument is null. What is "better"
contract is difficult to tell without better description of whole
context. Better description of whole context however is like i gave
(external device and its channels and the like). A part of program may
assert that such channel is between 0 and 4 or it may throw if it is
not between 0 and 4 or it may simply draw that 5 with red paint. All
about contract.

Ian Collins

unread,
Aug 27, 2010, 8:40:28 PM8/27/10
to
On 08/28/10 12:15 PM, 嘱 Tiib wrote:
> On 28 aug, 02:47, Ian Collins<ian-n...@hotmail.com> wrote:

That isn't the topic of this sub-thread. it all started with

"Assertions ("bug catchers" if you will) can be mapped to exceptions for
a release build to facilitate reporting to the developer, for example."

Which unfortunately got snipped.

My argument is that this is seldom, if ever a good idea because the
context of the exception is lost and unwinding can do more damage.

--
Ian Collins

Öö Tiib

unread,
Aug 28, 2010, 7:13:17 AM8/28/10
to
On 28 aug, 03:40, Ian Collins <ian-n...@hotmail.com> wrote:

> On 08/28/10 12:15 PM, Öö Tiib wrote:
>
>
>
> > On 28 aug, 02:47, Ian Collins<ian-n...@hotmail.com>  wrote:

Sorry, then i misunderstood. Yes i agree with you. Especially in
release build? Maybe there is some sort of platform weakness/
peculiarity. Like ... some platform that reboots on assert? You can
usually create a process from other process that can facilitates crash-
reporting and also keeps a backup ready that replaces the crashed
process. Maybe for testing ... like an unit-test that detects
assertions being there?

jacob navia

unread,
Aug 28, 2010, 3:06:57 PM8/28/10
to
Le 24/08/10 08:38, thomas a écrit :
> 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.
>
> 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?
> -------------
> char *p;
> string str(p, 20);
> -----------
>
> (Don't teach me the benefits of exceptions)
>
> --tom

I am currently developing a container library in C. Since C doesn't
support exceptions, maybe people here can be interested in a different
approach to exceptions and error handling.

The basic design is that each container function (method in the C++
terminology) calls a function if an error occurs. This function call is
the result of a lookup of several "stages":

(1) Each container contains a special "ErrorFunction" field that can be
set by the user after the container is created. This field contains a
function pointer to the function that will be called in case of an
error. This field is initialized by default to the default error
function by the creation procedure

(2) The library has a default error interface for errors that happen
during the creation function. This default error interface can also be
changed dynamically by the user at any time.

If the function call returns, the container returns an error code in
most cases or NULL if there is a single return value.

To obtain a behavior similar to C++ exceptions it suffices to set a jump
context with setjmp and store it in some global. If an error occurs, the
error function just jumps into the recovery context.

The default error function prints the error in standard error and returns 0.

joe

unread,
Aug 28, 2010, 4:52:10 PM8/28/10
to
jacob navia wrote:
> Le 24/08/10 08:38, thomas a écrit :
>> 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.
>>
>> 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?
>> -------------
>> char *p;
>> string str(p, 20);
>> -----------
>>
>> (Don't teach me the benefits of exceptions)
>>
>> --tom
>
> I am currently developing a container library in C. Since C doesn't
> support exceptions, maybe people here can be interested in a different
> approach to exceptions and error handling.
>
> The basic design is that each container function (method in the C++
> terminology) calls a function if an error occurs. This function call
> is the result of a lookup of several "stages":
>
> (1) Each container contains a special "ErrorFunction"

Too much space overhead considering that containers are the low level
(one step above primitives): 4 bytes (32-bit platform) or 8 bytes (64-bit
platform). Consider that one may want to create a hash table and use the
list container for the bucket chains. It just doesn't "feel" right have
all those 8-byte pointers (64-bit is coming on strong in the desktop
world.. who buys a new computer with a 32-bit OS anymore?) all over the
place, especially since they are not there for mainline purposes (!).

> field that can be set by the user after the container is created.

I think you should consider per library error handling rather than per
container. "library" may mean "tree container library" rather than "every
container under the sun library" depending on how you are able to
architect things.

>This field contains a
> function pointer to the function that will be called in case of an
> error. This field is initialized by default to the default error
> function by the creation procedure
>
> (2) The library has a default error interface for errors that happen
> during the creation function. This default error interface can also be
> changed dynamically by the user at any time.
>
> If the function call returns, the container returns an error code in
> most cases or NULL if there is a single return value.
>
> To obtain a behavior similar to C++ exceptions it suffices to set a
> jump context with setjmp and store it in some global. If an error
> occurs, the error function just jumps into the recovery context.

The setjmp/longjmp "exception" libraries are many and decidely
undesireable because setjmp/longjmp are not portable. (What it would take
to make them portable however, I don't know). setjmp/longjmp are
definitely C and definitely not C++ (de facto).

All said, the above kind of stuff is for C. The problem is solved in C++.
C containers are great for C, until they try to look like C++ containers.
There's a line of demarcation in there somewhere (of which when one
crosses it, it is best to write it in C++ rather than C).

jacob navia

unread,
Aug 28, 2010, 5:27:20 PM8/28/10
to
Le 28/08/10 22:52, joe a écrit :
> jacob navia wrote:

>>
>> (1) Each container contains a special "ErrorFunction"
>
> Too much space overhead considering that containers are the low level
> (one step above primitives): 4 bytes (32-bit platform) or 8 bytes (64-bit
> platform). Consider that one may want to create a hash table and use the
> list container for the bucket chains. It just doesn't "feel" right have
> all those 8-byte pointers (64-bit is coming on strong in the desktop
> world.. who buys a new computer with a 32-bit OS anymore?) all over the
> place, especially since they are not there for mainline purposes (!).
>

Excuse me but that is a very strange argument considering that C++
exception handling is a great consumer of space! The extremely detailed
tables that the compiler must emit for each function and for each scope
(including those functions that do NOT use exception handling) can take
up to 5-15% of the code size in many applications [1]. THAT is a space
problem that nowadays is taken for granted. Comparing those huge tables
to a single 8 byte pointer in each container is... well, let's forget
it. :-)


>> field that can be set by the user after the container is created.
>
> I think you should consider per library error handling rather than per
> container.

This is done automatically. The creation function (constructor in C++)
initializes the error handler of each container with the default error
handler stored in the library wide error interface. In most cases you
should just replace the library wide error handler with your error
function and you are all set. ALl containers will automatically use your
function since at creation time the global error handler is copied in
each container.

This design allows for customization of each individual container error
handler, what is not possible in C++. (As far as I know, please correct
me if I am wrong, I am not a C++ expert)

"library" may mean "tree container library" rather than "every
> container under the sun library" depending on how you are able to
> architect things.
>

see above.

>
> The setjmp/longjmp "exception" libraries are many and decidely
> undesireable because setjmp/longjmp are not portable. (What it would take
> to make them portable however, I don't know). setjmp/longjmp are
> definitely C and definitely not C++ (de facto).
>

The setjmp and longjmp functions are part of the C standard library and
are supported in all C implementations with the same semantics without
any exceptions.

In some environments, C++ compilers use inlined versions of
setjmp/longjmp for C++ exception handling. Specifically Cygwin g++
for instance.

> All said, the above kind of stuff is for C. The problem is solved in C++.
> C containers are great for C, until they try to look like C++ containers.

Yes, that is why I do not try to look like C++ containers but as C
containers.

The code can be downloaded for free from:

http://www.cs.virginia.edu/~lcc-win32/container.html

Full documentation is included.

---------------------------------
References:

[1]
http://stackoverflow.com/questions/691168/how-much-footprint-does-c-exception-handling-add
<quote>
The size complexity overhead isn't easily quantifiable but Eckel states
an average of 5 and 15 percent. This will depend on the size of your
exception handling code in ratio to the size of your application code.
If your program is small then exceptions will be a large part of the
binary.
<end quote>

The figure of 10% is confirmed in

choices.cs.uiuc.edu/exceptions.pdf

James Kanze

unread,
Aug 28, 2010, 6:29:53 PM8/28/10
to
On Aug 27, 6:19 am, "joe" <jc1...@att.net> wrote:
> RB wrote:
> > Found the answser to my error bug question.
> > Error: Is an undesirable deviation from requirements or Cosmetic .

> > Bug: Is an error found BEFORE the application goes into production or
> > missing Functionality.
> > Defect :Is an error found AFTER the application goes into production
> > or missing Requirement

> I don't agree with those definitions, and they seem a bit "lofty".

They sound rather "artificial". Maybe specific definitions
introduced locally in order to characterize problems.

> "bug/defect", "tomato/tomoto", they mean the same thing to me.
> That one tries to get all the bugs out before release doesn't
> factor into the definition for me, nor does it make me want
> multiple terms based upon the discovery time of the bug.

> In C++, "errors" are expected and defined things (though
> probably occur rarely) that one can manage with the exception
> machinery (or some other facilities, perhaps that which one
> built themself). Errors are detectable while bugs are not (but
> they can be flushed out by testing and reduced via good coding
> practices).

"Errors" are something that occurs but which shouldn't occur (in
an ideal world). Programming errors are made by programmers,
writing the code, and in general, can't be handled in the code
(because the presense of such errors means that we don't know
the current state of the program). Another word (probably
better) for such errors is defects. Other errors (dropped
connections, errors reading files, etc.) may be due to defects
in other equiment connected to the machine, but there's no
reason to abort everything when they occur. Other things, like
insufficient memory, are processed as "errors", since their
impact on the program is very much like that of a defect in
other equipment. And of course, there are user errors. And
hardware errors in the equipment you're running on. (One of the
most difficult errors I ever had to track down was a hardware
design error which resulted in one bit in the generated machine
code changing---about once every three or four hours.)

Before talking about appropriate strategy, I think you have to
rigorously defined what types of errors you're talking about. I
like the term "defects" for errors in the system you deliver (as
opposed to defects or failures in connecting equipment, or user
error), and errors for the rest. But even then, I wouldn't
ignore the fact that a defect in the software is always due to a
human error in the development process. Somebody made a
mistake, and at least to me, a "bug" sounds to impersonal,
random and caused by some external factor, which is not the
case.

--
James Kanze

James Kanze

unread,
Aug 28, 2010, 6:33:01 PM8/28/10
to
On Aug 26, 6:59 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> Goran Pusic wrote:

[...]


> > On Aug 26, 10:26 am, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> > The number of "other types" of try/catch statements in code is IMO
> > very, very small. And the bigger the code base, the smaller it is
> > (compared to said size).

> Hm, I am not so sure about that. It very much depends on how
> religiously and locally you handle exceptions. On one extreme
> end, you let everything propagate to the top-level and have
> one catch-all block. On the other end of the spectrum, you can
> handle each exception as early as possible. In the later case,
> you will still have a sizable number of catch blocks.

In the later case, you should probably be using return codes,
instead of exceptions?

--
James Kanze

James Kanze

unread,
Aug 28, 2010, 6:38:09 PM8/28/10
to

An exception, by definition, modifies state as it propagates up
the stack. It may (and usually will) also take actions, which
if the state of the program is corrupt, may be different from
the expected actions, resulting in further damage. Except in a
few special cases, an assertion failure must result in the
program terminating as quickly as possible, and doing as little
as possible before terminating. Period.

After that, we'd like as much information as possible about the
context when the assertion failure occured. On any reasonable
system, that will also result if the program is immediately
aborted.

--
James Kanze

James Kanze

unread,
Aug 28, 2010, 6:43:45 PM8/28/10
to
On Aug 27, 11:16 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
> Ian Collins wrote:
> > On 08/28/10 09:47 AM, joe wrote:
> >> Ian Collins wrote:

[...]


> >> A programmer is free to make his exception classes as
> >> elaborate as he wants to. Attach a stack trace, for
> >> example, if he wants to.

> > Which is what I said. But no matter how elaborate the
> > exception is, if the stack is munted, or memory is exhausted
> > or <insert bad things here> when it is thrown, it is still
> > worse than useless.

> True, but not really relevant is this context, or is it? Here,
> the focus is on exceptions that replace asserts. If your
> application suffers from a corrupted stack, you are in UB land
> anyway and neither asserts nor exceptions will handle that
> gracefully.

Gracefully, no. (By definition, an assertion failure isn't
graceful.) But an assertion failure (an abort) will generally
provide you with more information than exceptions. Of course,
if the stack is truly corrupt, an exception will result in
something like a segment violation or an out of bounds memory
access, which will result in pretty much the same thing as an
abort.

> Thus, I don't see how that says anything on the alternative of
> reporting the manifestation of a bug via asserts or
> exceptions.

The essential difference is that in the case of an assertion
failure, you've not executed the additional code of a stack
walkback, with the possibility of having made things worse.

--
James Kanze

Kai-Uwe Bux

unread,
Aug 28, 2010, 7:18:38 PM8/28/10
to
James Kanze wrote:

Often, indeed. But I think, there are cases when "as early as possible" is
not "immediately".

Also: when designing a library, you often cannot predict all use cases. If
you settle on signaling errors via return codes, you presuppose that
checking on return is the right thing to do for the client. Sometimes, you
can be sure of that. In other cases, throwing an exception offers some
flexibility to client code. Thus, you may even encounter the situation where
the library designer decided (rationally) that throwing would be better; yet
the client code programmer decides (also rationally) to check immediately
for the thrown exception.


Best

Kai-Uwe Bux

Kai-Uwe Bux

unread,
Aug 28, 2010, 7:30:01 PM8/28/10
to
James Kanze wrote:

Unfortunately, some context got lost:

joe wrote:
> Assertions ("bug catchers" if you will) can be mapped to exceptions for a
> release build to facilitate reporting to the developer, for example.

You are correct in that a core dump will provide more information than an
exception. However, the case under consideration here is when the program
crashes on a computer of a client. In very many cases, that means that no
core dump is generated (because of local settings) or that the user would
not mail it to you. The problem therefore is not "which way of reporting a
bug generates the best information for debugging" but "which way of
reporting a bug ensures or at least makes it likely that useful information
is forwarded to the programmer".

The way I understand Joe's proposition is to consider exceptions as a means
to that end.

>> Thus, I don't see how that says anything on the alternative of
>> reporting the manifestation of a bug via asserts or
>> exceptions.
>
> The essential difference is that in the case of an assertion
> failure, you've not executed the additional code of a stack
> walkback, with the possibility of having made things worse.

It would seem likely that a redefinition of the assert() macro should also
be considered: one that makes it really easy for the user to get all
essential information to the programmer. Ideally, it would print a bug
report including a destination e-mail address.


Best

Kai-Uwe Bux

joe

unread,
Aug 28, 2010, 11:27:47 PM8/28/10
to
James Kanze wrote:
> On Aug 27, 6:19 am, "joe" <jc1...@att.net> wrote:
>> RB wrote:
>>> Found the answser to my error bug question.
>>> Error: Is an undesirable deviation from requirements or Cosmetic .
>
>>> Bug: Is an error found BEFORE the application goes into production
>>> or missing Functionality.
>>> Defect :Is an error found AFTER the application goes into production
>>> or missing Requirement
>
>> I don't agree with those definitions, and they seem a bit "lofty".
>
> They sound rather "artificial". Maybe specific definitions
> introduced locally in order to characterize problems.
>
>> "bug/defect", "tomato/tomoto", they mean the same thing to me.
>> That one tries to get all the bugs out before release doesn't
>> factor into the definition for me, nor does it make me want
>> multiple terms based upon the discovery time of the bug.
>
>> In C++, "errors" are expected and defined things (though
>> probably occur rarely) that one can manage with the exception
>> machinery (or some other facilities, perhaps that which one
>> built themself). Errors are detectable while bugs are not (but
>> they can be flushed out by testing and reduced via good coding
>> practices).
>
> "Errors" are something that occurs but which shouldn't occur (in
> an ideal world).

I wouldn't say "shouldn't". I mean, sure, you don't want the hard disk to
fail, but very many do. I'd prefer a definition of "error" something more
akin to "an error is something you have to contingently plan for".

> Programming errors are made by programmers,

Oh, those are bugs, not "errors" (not the way I was using "error" and how
I was specifically trying to make the distinction between exactly that as
compared to those expected things that you have to contingently plan
for).

> writing the code, and in general, can't be handled in the code
> (because the presense of such errors means that we don't know
> the current state of the program).

Repeating what I said can't hurt.

> Another word (probably
> better) for such errors is defects.

Well, to me that conjures up quality control from the '80s, so I just use
"bug", which is certainly the field's chosen term for such.

> Other errors (dropped
> connections, errors reading files, etc.) may be due to defects
> in other equiment connected to the machine, but there's no
> reason to abort everything when they occur.

Now those are examples of "errors" (not "bugs").

> Other things, like
> insufficient memory, are processed as "errors", since their
> impact on the program is very much like that of a defect in
> other equipment.

Yes, still "errors" to be planned for.

> And of course, there are user errors.

Of course, some users ARE errors! (But I digress). ;)

> And
> hardware errors in the equipment you're running on. (One of the
> most difficult errors I ever had to track down was a hardware
> design error which resulted in one bit in the generated machine
> code changing---about once every three or four hours.)

How much of the universe a given program/system considers is
application-specific.

>
> Before talking about appropriate strategy, I think you have to
> rigorously defined what types of errors you're talking about.

Identification and categorization of errors is indeed one step of a
handful that are needed for a comprehensive error "handling" plan. Before
identification of specific errors though, one needs a good grasp of the
larger scope of where the program/system resides, so in that respect
strategy definitely comes first (top-down, rather than bottom-up). It may
be "taken for granted" in mature organizations/teams/developers, but to
exclude commenting on it would surely leave some thrashing for solution
too long from a bottom-up path.

> I
> like the term "defects" for errors in the system you deliver (as
> opposed to defects or failures in connecting equipment, or user
> error), and errors for the rest.

I like "bug", and I think it is the clearest term. It IS a bit more,
shall we say, "direct", though, as in: "I paid money for this buggy
software?! Fix the @#x& bugs!!". Rather then the much more milder term
you suggested that surely would be only spoken by the voice that says,
"Level 4, failed. You have, 2, more lives remaining" (ref: Minute to Win
It).

> But even then, I wouldn't
> ignore the fact that a defect in the software is always due to a
> human error in the development process.

I'm not sure I like that outlook on things! As much as there are many
formal processes and methods and levels, I'd stick out a few bugs and buy
software from the guy who could use a few bucks (obviously not for the
flight control system on the airplane I board, duh). All said, different
domains require different strategies, methods and techniques.

> Somebody made a
> mistake, and at least to me, a "bug" sounds to impersonal,
> random and caused by some external factor, which is not the
> case.

Ohhhhh.... I get it now, you think that bugs are always somebody's FAULT.
Eww-k. (I'm gonna leave that there, because I want to say something in
response to it and feel if I don't say anything I will have implicitly
responded to it be not saying anything, even though it may be taken the
wrong way.)


joe

unread,
Aug 28, 2010, 11:36:47 PM8/28/10
to
James Kanze wrote:
> On Aug 27, 11:16 pm, Kai-Uwe Bux <jkherci...@gmx.net> wrote:
>> Ian Collins wrote:
>>> On 08/28/10 09:47 AM, joe wrote:
>>>> Ian Collins wrote:
>
> [...]
>>>> A programmer is free to make his exception classes as
>>>> elaborate as he wants to. Attach a stack trace, for
>>>> example, if he wants to.
>
>>> Which is what I said. But no matter how elaborate the
>>> exception is, if the stack is munted, or memory is exhausted
>>> or <insert bad things here> when it is thrown, it is still
>>> worse than useless.
>
>> True, but not really relevant is this context, or is it? Here,
>> the focus is on exceptions that replace asserts. If your
>> application suffers from a corrupted stack, you are in UB land
>> anyway and neither asserts nor exceptions will handle that
>> gracefully.
>
> Gracefully, no. (By definition, an assertion failure isn't
> graceful.)

But, by definition, probably better than the consequence of the unknown
that was about to ensue. As in, "He just seems to have driven off the
cliff" vs. "That guardrail saved his life". The man still alive won't be
going back and confronting the guardrail about it's lack of "grace". So,
decidely then (yes?), guardrails do not have to be "graceful".


joe

unread,
Aug 28, 2010, 11:53:09 PM8/28/10
to

Welllll, probably. I don't do it that way so I wouldn't know. I was under
the impression that some people (those who use exceptions as much as I
use "if" ;)) do it that way. I leave assertions in release code but
change the handling (I've never done the "notify an admin" thing, but I
hope to! As it stands, I LOG assertion failures after a msg to the user
(if there is one) declaring that the world is about to end and to shut
off their computer with the power switch immediately because their
computer is the cause of the end of the world).

>
>>> Thus, I don't see how that says anything on the alternative of
>>> reporting the manifestation of a bug via asserts or
>>> exceptions.
>>
>> The essential difference is that in the case of an assertion
>> failure, you've not executed the additional code of a stack
>> walkback, with the possibility of having made things worse.
>
> It would seem likely that a redefinition of the assert() macro should
> also be considered: one that makes it really easy for the user to get
> all essential information to the programmer. Ideally, it would print
> a bug report including a destination e-mail address.

I didn't consider unwinding when I wrote the "mapping assertions to
exceptions" thing. "Largely", I do consider "exception" to be equivalent
to abort (or wish it to be so) (abort after that which I want to precede
"abort").


joe

unread,
Aug 28, 2010, 11:58:31 PM8/28/10
to

Yeah. I "missed" that when I posted. Yeah, I'm still resisting
exceptions.

>
> After that, we'd like as much information as possible about the
> context when the assertion failure occured.

Is a stack trace "low hanging fruit"? Yeah, yeah.. IDE's... I was doing
it before IDEs and my code is instrumented to produce such, simply.

> On any reasonable
> system, that will also result if the program is immediately
> aborted.

What will?


It is loading more messages.
0 new messages