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

Assertion vs Exception Handling

80 views
Skip to first unread message

DT

unread,
Mar 8, 2010, 10:32:08 PM3/8/10
to
1. I have a long array and I want to check element of the array fails
my test, for example:

for (int i ...) {
if (a[i]==0) {
cout << "failed " << i << "\n"; break;
}
}

Plus, I only want to compile this error checking code in the debug
mode. If I can use assertion, how to do it? Otherwise, should I use
exception handling and how?

2. If an assertion fails before the cleanup code (i.e. freeing the
pointers), would I experience memory leak? If so, how to avoid such
problems?

Thanks.

Sprechen sie von C++

unread,
Mar 8, 2010, 11:30:27 PM3/8/10
to
you can use #defines to block off debug code that will not be included in
the release.

You could make you code error tolerate with the try/catch approach.


--
http://contract-developer.dyndns.biz

"DT" <dongt...@gmail.com> wrote in message
news:4f135847-b4f7-4a9b...@x22g2000yqx.googlegroups.com...

Vladimir Jovic

unread,
Mar 9, 2010, 3:22:53 AM3/9/10
to
DT wrote:
> 1. I have a long array and I want to check element of the array fails
> my test, for example:
>
> for (int i ...) {
> if (a[i]==0) {
> cout << "failed " << i << "\n"; break;
> }
> }
>
> Plus, I only want to compile this error checking code in the debug
> mode. If I can use assertion, how to do it? Otherwise, should I use
> exception handling and how?


http://www.parashift.com/c++-faq-lite/exceptions.html
http://linux.die.net/man/3/assert

>
> 2. If an assertion fails before the cleanup code (i.e. freeing the
> pointers), would I experience memory leak? If so, how to avoid such
> problems?

If the assertion fails, the OS will clean up.

Daniel T.

unread,
Mar 9, 2010, 9:52:06 AM3/9/10
to
DT <dongt...@gmail.com> wrote:

> 1. I have a long array and I want to check element of the array fails
> my test, for example:
>
> for (int i ...) {
> if (a[i]==0) {
> cout << "failed " << i << "\n"; break;
> }
> }
>
> Plus, I only want to compile this error checking code in the debug
> mode. If I can use assertion, how to do it? Otherwise, should I use
> exception handling and how?

Read section 24.3.7.2 in "The C++ Programming Language" by Stroustrup.

> 2. If an assertion fails before the cleanup code (i.e. freeing the
> pointers), would I experience memory leak? If so, how to avoid such
> problems?

You don't have to worry about memory leaks, but there may be other
cleanup or state saving that needs to happen that wont.

For your example, I suggest something like (a variation of Stroustrup's
code):

template <typename X>
inline void Assert(bool assertion)
{
if (!assertion)
throw X();
}

Then where needed:

Assert<std::exception>(NDEBUG || find(a.begin(), a.end(), 0) ==
a.end());

Leigh Johnston

unread,
Mar 9, 2010, 10:34:23 AM3/9/10
to

> Then where needed:
>
> Assert<std::exception>(NDEBUG || find(a.begin(), a.end(), 0) ==
> a.end());

If NDEBUG is undefined (as will be the case with debug builds) then the
above is a syntax error.

/Leigh

Daniel T.

unread,
Mar 9, 2010, 12:15:36 PM3/9/10
to
"Leigh Johnston" <le...@i42.co.uk> wrote:

From the book ("The C++ Programming Language" by Bjarne Stroustrup):

Using NDEBUG in this way requires that we define NDEBUG with a suitable
value whether or not we are debugging. A C++ implementation does not do
this for us by default, so it is better to use a value. For example:

#ifdef NDEBUG
const bool ARG_CHECK = false; // we are not debugging: disable checks
#else
const bool ARG_CHECK = true; // we are debugging #endif

void f3(int* p)
{
Assert<Bad_arg>(!ARG_CHECK || p!=0);
// either I�m not debugging or p!=0
//...
}

Read the entirety of section 24.3.7.2 for more information.

Leigh Johnston

unread,
Mar 9, 2010, 12:20:04 PM3/9/10
to

"Daniel T." <dani...@earthlink.net> wrote in message
news:daniel_t-C35059...@70-3-168-216.pools.spcsdns.net...

Yes, like I said, what you posted was a syntax error.

/Leigh

John H.

unread,
Mar 9, 2010, 4:14:25 PM3/9/10
to
On Mar 8, 9:32 pm, DT <dongta....@gmail.com> wrote:
> If I can use assertion, how to do it?

There is a standard assert macro provided by #include <cassert>. When
the symbol NDEBUG (think "non-debug") is not defined, assert will
evaluate its argument and if it is false, it will print a brief
diagnostic message and abort the program. When the symbol NDEBUG is
defined, assert does nothing (not even evaluate the argument).
Depending on your development environment, it may offer its own
version of assert, or it may handle asserts differently (for instance,
in a debugger, it might break at the point of a failed assert to give
you a chance to study the situation). You could also create your own
assert mechanism that may have different behavior, as other posters
have discussed.

#include <cassert>
#include <iostream>
void print_name(char const * name)
{
assert(name != NULL);
assert(strlen(name) > 0);
std::cout << name << std::endl;
}

You may find it useful to put some text describing the situation
inside the assert:
assert(name!=NULL && "print_name requires a valid pointer");
This is a trick that relies on the fact that the string literal will
always evaluate to true, so anding it with your test won't change the
logic of your test, but this little description can appear in the
diagnostic message provided when the program aborts.

> should I use exception handling and how?

Exceptions can get more complicated. I am not up to a thorough
discussion of them, but I will touch upon them. You can perform
tests, and then throw exceptions, which functions higher up the call
stack may catch and act upon. If no one catches it, the program will
terminate. The above example, with exceptions, might look like:

#include <stdexcept>
#include <iostream>
void print_name(char const * name)
{
if(name == NULL)
throw std::invalid_argument("print_name invalid ptr");
if(strlen(name) < 1)
throw std::length_error("print_name empty name");
std::cout << name << std::endl;
}

A couple things to consider:
- Ease of use:
asserts are simple. You can put in an assert, and it helps you spot
bugs while you run the program. Little development time is spent.
exceptions are more complicated. It's easy to throw an exception, but
that action can cause behavior (via a catch) that might effect the way
the error is seen, and make it harder to track down the origin of the
problem.
This is actually something to think about. Development time is a real
cost in software. Also, if you find one technique a lot of trouble to
use, you may find yourself skipping over programming in such tests
that you will regret later on ("Obviously name isn't going to be
empty, that is just silly, everyone has a name. I am not going to
check for it.").
* Note, the operating system will still clean up some things (like
dynamic memory allocation), but other things that you might want done
(perhaps gracefully closing a network connection) may not happen.

- Flexibility:
asserts offer little flexibility. They are for debug mode only. When
an error is detected, the program is aborted. No destructors are
called, so things might not clean up neatly*.
exceptions offer much flexibility. They will be active in both debug
and release mode. They give a chance for more complicated error
handling. For instance, print_name might throw an exception because
it doesn't have name, but whoever called print_name might be able to
catch it, and add more information to the diagnostic. Destructors are
called so things will clean up more completely.

Another thing you might consider is how serious is the problem. For
instance, say I have an option for the user to get info about the
program, display version number, who it is registered to, etc. If the
code executes, and there is no name, me as a programmer might find it
nice for execution to hault so this unusual state can be brought to my
attention and I can look to see what might be wrong. As an end user,
having a name in an About Box probably isn't a big deal. I certainly
don't want the program to terminate (like an uncaught exception would
do).
In constrast, if I have a function that is about to use a pointer,
dereferencing an invalid pointer could cause the program to crash in
an uncontroled manner, so I probably don't want the user to ever
experience this. In this scenario, an exception might be better.
So here is an example that uses both techniques:
void print_name(char const * name)
{
if(name == NULL)
throw std::invalid_argument("print_name invalid ptr");
assert(strlen(name)>0 && "print_name empty name");
}

Finally, your development environment might also push you one way or
another. Some debuggers will make it more useful to use asserts to
debug, whilst some will make it easier to use exceptions. Play around
and see which one you find more intuitive.

James Kanze

unread,
Mar 11, 2010, 6:06:52 PM3/11/10
to
On Mar 9, 3:32 am, DT <dongta....@gmail.com> wrote:
> 1. I have a long array and I want to check element of the array fails
> my test, for example:

> for (int i ...) {
> if (a[i]==0) {
> cout << "failed " << i << "\n"; break;
> }
> }

Define what you mean by "fails". Can the case only occur
because of a programming error? Can it occur because of e.g.
resource limitations (insufficient memory, etc.)? Or as a
result of bad user input?

> Plus, I only want to compile this error checking code in the
> debug mode.

Why? That doesn't normally make sense.

> If I can use assertion, how to do it?

Just
assert(a[i] == 0);

But most of the time, assertions will be active in released
code.

> Otherwise, should I use exception handling and how?

Whether exception handling or assertions are more appropriate
depends on the type of error and the application domain. And
possibly other considerations as well.

> 2. If an assertion fails before the cleanup code (i.e. freeing
> the pointers), would I experience memory leak? If so, how to
> avoid such problems?

An assertion failure terminates your program brutally, with an
abort. The system will clean up most things correctly. And in
cases justifying an assertion failure, you might not want to
clean up others---having the temporary files can help localize
the error.

--
James Kanze

Leigh Johnston

unread,
Mar 12, 2010, 5:36:22 AM3/12/10
to

"James Kanze" <james...@gmail.com> wrote in message
news:3494792b-bcd9-4426...@y17g2000yqd.googlegroups.com...


> On Mar 9, 3:32 am, DT <dongta....@gmail.com> wrote:
>> 1. I have a long array and I want to check element of the array fails
>> my test, for example:
>
>

> Just
> assert(a[i] == 0);
>
> But most of the time, assertions will be active in released
> code.
>

Sigh. What do you mean most of the time? We have been over this before.
By default assert does nothing in release mode which is the way it should
be. Release mode = NDEBUG = "not debugging" = no op assert.

/Leigh

Ian Collins

unread,
Mar 12, 2010, 6:21:18 AM3/12/10
to
On 03/12/10 11:36 PM, Leigh Johnston wrote:

> "James Kanze" <james...@gmail.com> wrote:
>>
>> But most of the time, assertions will be active in released
>> code.
>
> Sigh. What do you mean most of the time? We have been over this before.
> By default assert does nothing in release mode which is the way it
> should be. Release mode = NDEBUG = "not debugging" = no op assert.

That depends how you define "release mode"

Most of the software I have released was released with assertion on and
most of the code I use (including my preferred C++ compiler) has them
enabled.

I'd rather have a bug report with a core file than one without.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 7:21:17 AM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message
news:7vuml0...@mid.individual.net...

Release mode asserts are desirable only when a higher degree of
defensiveness is required which depends on the application domain in
question. There is a reason why assert does nothing when NDEBUG is defined.

/Leigh

Michael Doubez

unread,
Mar 12, 2010, 8:46:57 AM3/12/10
to
On 12 mar, 13:21, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Ian Collins" <ian-n...@hotmail.com> wrote in message

>
> news:7vuml0...@mid.individual.net...
>
>
>
> > On 03/12/10 11:36 PM, Leigh Johnston wrote:
> >> "James Kanze" <james.ka...@gmail.com> wrote:
>
> >>> But most of the time, assertions will be active in released
> >>> code.
>
> >> Sigh. What do you mean most of the time? We have been over this before.
> >> By default assert does nothing in release mode which is the way it
> >> should be. Release mode = NDEBUG = "not debugging" = no op assert.
>
> > That depends how you define "release mode"
>
> > Most of the software I have released was released with assertion on and
> > most of the code I use (including my preferred C++ compiler) has them
> > enabled.
>
> > I'd rather have a bug report with a core file than one without.
>
> > --
> > Ian Collins
>
> Release mode asserts are desirable only when a higher degree of
> defensiveness is required which depends on the application domain in
> question.

I would say the definition is the contrary: a program without assert
is possible only when a inconsistent state of the program is
admissible.

I would say it is only possible for programs that don't modify a state
(such as the program ls) and for which you don't care about locating
bug on the user's plateform.

>  There is a reason why assert does nothing when NDEBUG is defined.

Because the C standard dictates that when NDEBUG is defined, the
assert macro shall expand to nothing.

NDEBUG has no other effect or meaning whatsoever.

But I find relevant that the assert() are activated by default and it
is a defines that disables them. If assert() was only a debug feature,
I would have expected the reverse: DEBUG enabling asserts.

--
Michael

Leigh Johnston

unread,
Mar 12, 2010, 9:38:11 AM3/12/10
to

"Michael Doubez" <michael...@free.fr> wrote in message
news:f6db8690-71d0-4cbf...@g26g2000yqn.googlegroups.com...


> On 12 mar, 13:21, "Leigh Johnston" <le...@i42.co.uk> wrote:
>> "Ian Collins" <ian-n...@hotmail.com> wrote in message
>>
>> news:7vuml0...@mid.individual.net...
>>
>>
>>
>> > On 03/12/10 11:36 PM, Leigh Johnston wrote:
>> >> "James Kanze" <james.ka...@gmail.com> wrote:
>>
>> >>> But most of the time, assertions will be active in released
>> >>> code.
>>
>> >> Sigh. What do you mean most of the time? We have been over this
>> >> before.
>> >> By default assert does nothing in release mode which is the way it
>> >> should be. Release mode = NDEBUG = "not debugging" = no op assert.
>>
>> > That depends how you define "release mode"
>>
>> > Most of the software I have released was released with assertion on and
>> > most of the code I use (including my preferred C++ compiler) has them
>> > enabled.
>>
>> > I'd rather have a bug report with a core file than one without.
>>
>> > --
>> > Ian Collins
>>
>> Release mode asserts are desirable only when a higher degree of
>> defensiveness is required which depends on the application domain in
>> question.
>
> I would say the definition is the contrary: a program without assert
> is possible only when a inconsistent state of the program is
> admissible.

Nonsense, either be extremely defensive or not defensive at all, somewhere
inbetween is pointless and an assert before/after very state changing
function is overkill for lots of application domains.

> I would say it is only possible for programs that don't modify a state
> (such as the program ls) and for which you don't care about locating
> bug on the user's plateform.
>
>> There is a reason why assert does nothing when NDEBUG is defined.
>
> Because the C standard dictates that when NDEBUG is defined, the
> assert macro shall expand to nothing.
>
> NDEBUG has no other effect or meaning whatsoever.
>
> But I find relevant that the assert() are activated by default and it
> is a defines that disables them. If assert() was only a debug feature,
> I would have expected the reverse: DEBUG enabling asserts.

assert is a debug feature, the NDEBUG means "not debugging" and when we are
"not debugging" assert does nothing.

/Leigh

Ian Collins

unread,
Mar 12, 2010, 4:53:42 PM3/12/10
to
On 03/13/10 01:21 AM, Leigh Johnston wrote:

> "Ian Collins" <ian-...@hotmail.com> wrote:
>> On 03/12/10 11:36 PM, Leigh Johnston wrote:
>>> "James Kanze" <james...@gmail.com> wrote:
>>>>
>>>> But most of the time, assertions will be active in released
>>>> code.
>>>
>>> Sigh. What do you mean most of the time? We have been over this before.
>>> By default assert does nothing in release mode which is the way it
>>> should be. Release mode = NDEBUG = "not debugging" = no op assert.
>>
>> That depends how you define "release mode"
>>
>> Most of the software I have released was released with assertion on
>> and most of the code I use (including my preferred C++ compiler) has
>> them enabled.
>>
>> I'd rather have a bug report with a core file than one without.
>>
[please don't quote sigs]

>
> Release mode asserts are desirable only when a higher degree of
> defensiveness is required which depends on the application domain in
> question. There is a reason why assert does nothing when NDEBUG is defined.

Yes there is, you can turn them off. A lot of applications don't. It
may depend on the platform, but most Unix applications I use (and write)
have asserts on; as I said, a bug report with a core file than one
without. If used correctly, asserts trap the unexpected and protect the
integrity of the application's state. I bet whatever C++ compiler you
use has them turned on.

Release mode is a nebulous concept; it means different things to
different people.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 5:03:18 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvrmp...@mid.individual.net...

By default VC++ (a *very* popular C++ compiler) defines NDEBUG by default in
release builds.

It doesn't surprise me that unix apps tends to have NDEBUG turned off as
unix traditionally involves writing makefiles by hand so NDEBUG is something
you have to turn on rather than off. I wonder if any popular unix IDEs turn
NDEBUG on by default for release builds.

/Leigh

Leigh Johnston

unread,
Mar 12, 2010, 5:10:21 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvrmp...@mid.individual.net...

From Microsoft documentation:

The assert macro is typically used to identify logic errors during program
development by implementing the expression argument to evaluate to false
only when the program is operating incorrectly. After debugging is complete,
assertion checking can be turned off without modifying the source file by
defining the identifier NDEBUG. NDEBUG can be defined with a /D command-line
option or with a #define directive. If NDEBUG is defined with #define, the
directive must appear before ASSERT.H is included.

Notice the use of the word "typically". My point is that *typically* assert
is a debugging tool used during the development phase and only rarely
enabled for released product where a higher degree of defensiveness is
appropriate. Yes I admit I am a Microsoft fanboy. You are a unix fanboy.
Fanboys should probably be mostly ignored - but I don't give a fuck. :)

/Leigh

Ian Collins

unread,
Mar 12, 2010, 5:11:22 PM3/12/10
to
On 03/13/10 11:03 AM, Leigh Johnston wrote:
> "Ian Collins" <ian-...@hotmail.com> wrote:
>> On 03/13/10 01:21 AM, Leigh Johnston wrote:
>>>
>>> Release mode asserts are desirable only when a higher degree of
>>> defensiveness is required which depends on the application domain in
>>> question. There is a reason why assert does nothing when NDEBUG is
>>> defined.
>>
>> Yes there is, you can turn them off. A lot of applications don't. It
>> may depend on the platform, but most Unix applications I use (and
>> write) have asserts on; as I said, a bug report with a core file than
>> one without. If used correctly, asserts trap the unexpected and
>> protect the integrity of the application's state. I bet whatever C++
>> compiler you use has them turned on.
>>
>> Release mode is a nebulous concept; it means different things to
>> different people.

[please don't quote sigs]

> By default VC++ (a *very* popular C++ compiler) defines NDEBUG by
> default in release builds.

But I bet asserts are still enabled in the compiler its self.

> It doesn't surprise me that unix apps tends to have NDEBUG turned off as
> unix traditionally involves writing makefiles by hand so NDEBUG is
> something you have to turn on rather than off. I wonder if any popular
> unix IDEs turn NDEBUG on by default for release builds.

As I said, release builds means different things to different people.
Unix IDE typically don't do as much hand holding as the likes of VC++.
I've never released anything with assertion off, even on small embedded
platforms.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 5:18:03 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvsnu...@mid.individual.net...


> On 03/13/10 11:03 AM, Leigh Johnston wrote:
>> "Ian Collins" <ian-...@hotmail.com> wrote:
>>> On 03/13/10 01:21 AM, Leigh Johnston wrote:
>>>>
>>>> Release mode asserts are desirable only when a higher degree of
>>>> defensiveness is required which depends on the application domain in
>>>> question. There is a reason why assert does nothing when NDEBUG is
>>>> defined.
>>>
>>> Yes there is, you can turn them off. A lot of applications don't. It
>>> may depend on the platform, but most Unix applications I use (and
>>> write) have asserts on; as I said, a bug report with a core file than
>>> one without. If used correctly, asserts trap the unexpected and
>>> protect the integrity of the application's state. I bet whatever C++
>>> compiler you use has them turned on.
>>>
>>> Release mode is a nebulous concept; it means different things to
>>> different people.
>
> [please don't quote sigs]
>
>> By default VC++ (a *very* popular C++ compiler) defines NDEBUG by
>> default in release builds.
>
> But I bet asserts are still enabled in the compiler its self.
>

NDEBUG is defined by default for release builds when creating a new project
with VC++. assert is a no-op when NDEBUG is defined. I have no idea what
you mean by "asserts are still enabled in the compiler its self".
assert(foo) does nothing when NDEBUG is defined in VC++ which is as it
should be.

/Leigh

Ian Collins

unread,
Mar 12, 2010, 5:17:18 PM3/12/10
to
On 03/13/10 11:10 AM, Leigh Johnston wrote:
>
> From Microsoft documentation:
>
> The assert macro is typically used to identify logic errors during
> program development by implementing the expression argument to evaluate
> to false only when the program is operating incorrectly. After debugging
> is complete, assertion checking can be turned off without modifying the
> source file by defining the identifier NDEBUG. NDEBUG can be defined
> with a /D command-line option or with a #define directive. If NDEBUG is
> defined with #define, the directive must appear before ASSERT.H is
> included.

Yes, we all know what NDEBUG does, that's not the contentions issue.

> Notice the use of the word "typically". My point is that *typically*
> assert is a debugging tool used during the development phase and only
> rarely enabled for released product where a higher degree of
> defensiveness is appropriate. Yes I admit I am a Microsoft fanboy. You
> are a unix fanboy.

That's where I beg to differ, if you were to conduct a survey, you'd
probably be surprised how many application do ship with asserts on.
Games are probably an exception, but any application that manipulates
user data will want to verify the sanity of its internal state.

I don't develop for windows, but isn't it asserts that pop up that
dialogue box asking if you want to debug or abort (if you have VC++
installed) an application when it goes wrong?

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 5:22:45 PM3/12/10
to

"DT" <dongt...@gmail.com> wrote in message
news:4f135847-b4f7-4a9b...@x22g2000yqx.googlegroups.com...

If an assert fails there is usually no reason to worry about memory leaks as
asserts are normally used during the development phase to uncover bugs which
you need to fix before releasing your product. A failed assert should cause
your program to abort so memory leaks are the least of your problems. You
should not use asserts for valid runtime errors for which exceptions should
be used instead.

/Leigh

Ian Collins

unread,
Mar 12, 2010, 5:19:19 PM3/12/10
to
On 03/13/10 11:18 AM, Leigh Johnston wrote:
>
> NDEBUG is defined by default for release builds when creating a new
> project with VC++. assert is a no-op when NDEBUG is defined. I have no
> idea what you mean by "asserts are still enabled in the compiler its
> self". assert(foo) does nothing when NDEBUG is defined in VC++ which is
> as it should be.

When they build the compiler, they don't define NDEBUG. I'm sure I've
seen report of compiler assertions form VC++. I've certainly hit a few
in g++ and Sun CC.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 5:25:23 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvt32...@mid.individual.net...

That is what will happen if NDEBUG was not defined when the asserting
statement was compiled and the assert evaluates to false.

/Leigh

Leigh Johnston

unread,
Mar 12, 2010, 5:26:58 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvt6r...@mid.individual.net...

I have no idea what you are talking about. Who cares how the compiler was
built? It is irrelevant to building software with the compiler.

/Leigh

Ian Collins

unread,
Mar 12, 2010, 5:31:37 PM3/12/10
to
On 03/13/10 11:26 AM, Leigh Johnston wrote:
>
> "Ian Collins" <ian-...@hotmail.com> wrote:
>> On 03/13/10 11:18 AM, Leigh Johnston wrote:
>>>
>>> NDEBUG is defined by default for release builds when creating a new
>>> project with VC++. assert is a no-op when NDEBUG is defined. I have no
>>> idea what you mean by "asserts are still enabled in the compiler its
>>> self". assert(foo) does nothing when NDEBUG is defined in VC++ which is
>>> as it should be.
>>
>> When they build the compiler, they don't define NDEBUG. I'm sure I've
>> seen report of compiler assertions form VC++. I've certainly hit a few
>> in g++ and Sun CC.
>
> I have no idea what you are talking about. Who cares how the compiler
> was built? It is irrelevant to building software with the compiler.

It is completely relevant to the discussion as a counter example to your
point: "that *typically* assert is a debugging tool used during the

development phase and only rarely enabled for released product"

If something unexpected happens and the compiler's internal state
becomes corrupt, do you want it to generate bad code, fall in a heap or
bail with an assertion failure? As both a user and a developer, I know
which one I'd prefer.

--
Ian Collins

Ian Collins

unread,
Mar 12, 2010, 5:33:53 PM3/12/10
to
On 03/13/10 11:25 AM, Leigh Johnston wrote:
> "Ian Collins" <ian-...@hotmail.com> wrote:
>>
>> I don't develop for windows, but isn't it asserts that pop up that
>> dialogue box asking if you want to debug or abort (if you have VC++
>> installed) an application when it goes wrong?
>>
> That is what will happen if NDEBUG was not defined when the asserting
> statement was compiled and the assert evaluates to false.

I thought so.

So asserts are enabled in the likes of Word and Excel as well (I've seen
this dialogue from both). Which to my mind is a jolly good thing.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 5:41:08 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvttt...@mid.individual.net...

I misunderstood. Yes I agree, I already said there are exceptions where a
higher degree of defensiveness may be required and a compiler might be such
an exception as it can be used to compile software which might itself
require a higher degree of defensiveness. This doesn't change the fact that
assert is primarily a debugging aid.

/Leigh

Leigh Johnston

unread,
Mar 12, 2010, 5:43:01 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvu24...@mid.individual.net...

It is not a jolly good thing: it is indicative of the fact that Word and
Excel where probably released without sufficient testing. Perhaps being a
Microsoft fanboy is not such a good thing.

/Leigh

Paavo Helde

unread,
Mar 12, 2010, 5:51:30 PM3/12/10
to
"Leigh Johnston" <le...@i42.co.uk> wrote in
news:z_ydnc0Cn_BHJgfW...@giganews.com:

I agree with you - but Microsoft doesn't! They have the concept of
checked iterators, which is very similar to asserts, but not implemented
via assert(). And this feature is on also in Release builds by default.
One has to take extra steps to turn it off. Ok, I understand that as this
feature affects binary compatibility, they would like to to have the same
setting in Debug and Release builds so that the libraries from different
builds can be mixed. Though, I would consider a debugging feature
affecting the binary compatibility of libraries as a design failure.

The reason why I am not keen to keep debug asserts in release builds is
that in my experience the chance of a triggered debug assert to be a
false-alarm is significantly more than 50%. I guess this is caused by my
coding style (whenever in doubt, throw in a debug assert) together with
constantly changing business requirements.

Paavo

Leigh Johnston

unread,
Mar 12, 2010, 5:54:34 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvu24...@mid.individual.net...

Sorry I was mistaken, the dialog which pops up on a failed assert for VC++
runtime says "Assertion failed!" and "Abort/Retry/Ignore" but I don't know
how Word was built and with what runtime library. This might be a standard
crash dialog...

/Leigh

Ian Collins

unread,
Mar 12, 2010, 6:00:04 PM3/12/10
to
Ah, good we are on the same wavelength at last.

I still disagree with assert being primarily a debugging aid. Unit
tests should be the debugging tool, asserts are the safety net for those
unexpected events that can't be handled by the application's logic.

I may be biased coming from an embedded background, but one of the first
lessons an embedded developer learns is to expect the unexpected and
defend against it. A typical real example was a driver I wrote for a
serial device; according the data sheet, it was impossible for the data
read interrupt to fire with an empty input buffer. So I added an
assertion in the interrupt handler. Sure enough, in a customer site,
the product rebooted. The log showed that assert had triggered.

--
Ian Collins

Leigh Johnston

unread,
Mar 12, 2010, 6:10:25 PM3/12/10
to

"Paavo Helde" <myfir...@osa.pri.ee> wrote in message
news:Xns9D3A8FD5...@216.196.109.131...

I have checked iterators turned off. :)

/Leigh

Leigh Johnston

unread,
Mar 12, 2010, 6:13:56 PM3/12/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:7vvvj8...@mid.individual.net...

Actually I think embedded software is one of the exceptions where a higher
degree of defensiveness is required (especially where safety is a concern)
and a reboot is usually the best outcome for unexpected state. On the other
hand I have worked in the mobile phone industry and from what I can recall
we didn't use release mode asserts much.

/Leigh

James Kanze

unread,
Mar 13, 2010, 6:23:19 PM3/13/10
to
On Mar 12, 10:36 am, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "James Kanze" <james.ka...@gmail.com> wrote in message

> news:3494792b-bcd9-4426...@y17g2000yqd.googlegroups.com...

> > On Mar 9, 3:32 am, DT <dongta....@gmail.com> wrote:
> >> 1. I have a long array and I want to check element of the array fails
> >> my test, for example:

> > Just
> > assert(a[i] == 0);

> > But most of the time, assertions will be active in released
> > code.

> Sigh. What do you mean most of the time?

I mean most of the time in programs written by professional
programmers, using well established techniques for project
management.

Obvious, hobby programmers have their own rules, with which I'm
not familiar.

> We have been over this before.

Yes. The issue is pretty well established, and well documented
in the appropriate literature.

> By default assert does nothing in release mode which is the
> way it should be.

There is no real default, or at least not one applicable to any
real applications. Every application will decide what to do
with regards to all of the compiler options. Of course, the
very fact that one speaks of a "release mode" suggests
unprofessionalism. If at all possible, you "release" the code
you've tested, and there aren't different modes. (And when not
possible, there may be more than just two modes.)

--
James Kanze

James Kanze

unread,
Mar 13, 2010, 6:26:20 PM3/13/10
to
On Mar 12, 11:21 am, Ian Collins <ian-n...@hotmail.com> wrote:
> On 03/12/10 11:36 PM, Leigh Johnston wrote:

> > "James Kanze" <james.ka...@gmail.com> wrote:

> >> But most of the time, assertions will be active in released
> >> code.

> > Sigh. What do you mean most of the time? We have been over
> > this before. By default assert does nothing in release mode
> > which is the way it should be. Release mode = NDEBUG = "not
> > debugging" = no op assert.
>
> That depends how you define "release mode"

> Most of the software I have released was released with
> assertion on and most of the code I use (including my
> preferred C++ compiler) has them enabled.

> I'd rather have a bug report with a core file than one without.

And I'd rather release the executables that I've tested, rather
than something else. (One recent but I had to track down was
due to the fact that VC++ doesn't always call destructors when
optimization is turned on---in the Visual IDE's "release mode".
And that in the code in question, smart pointers were an
appropriate solution, and were being used.)

--
James Kanze

Robert Fendt

unread,
Mar 13, 2010, 6:39:20 PM3/13/10
to
And thus spake James Kanze <james...@gmail.com>
Sat, 13 Mar 2010 15:23:19 -0800 (PST):

> There is no real default, or at least not one applicable to any
> real applications. Every application will decide what to do
> with regards to all of the compiler options. Of course, the
> very fact that one speaks of a "release mode" suggests
> unprofessionalism. If at all possible, you "release" the code
> you've tested, and there aren't different modes. (And when not
> possible, there may be more than just two modes.)

Well, you do live in a very interestingly limited world it
seems. And labeling more or less everyone who does not agree
with you as unprofessional is quite an interesting statement as
well.

At my company, we _do_ have two different builds, one for
debugging and one for release. The application is very
performance-sensitive. In the debugging version, all sorts of
sanity checks and asserts are active, which slow the code down
by an additional factor of 5-10 (apart from the lack of
optimisation), but which help to make sure that the geometry
core is in fact doing something mathematically sane.

Apart from that, asserts do not always make sense in non-debug
code anyway. For example, I currently also develop a graphics
transformation library. If I build it with fully optimisation,
it becomes faster by a factor of 10-20 (among other things due
to massive inlining). However, it is more or less _impossible_
to debug when built fully optimised, so active asserts would not
do much good anyway.

By the way, the standard 'assert' macro defined in the standard
IIRC is explicitely disabled if 'NDEBUG' is defined, and setting
this preprocessor symbol also disables all sorts of range checks
etc. in STL containers at least in VC++, if I am not mistaken.
So in my opinion it could in fact be quite common that asserts
are inactive in production code, at least if it is
performance-critical code built with full optimisation.

Regards,
Robert

Leigh Johnston

unread,
Mar 13, 2010, 6:39:43 PM3/13/10
to

"James Kanze" <james...@gmail.com> wrote in message
news:7ca365f4-2c95-4d61...@y17g2000yqd.googlegroups.com...

"Release mode" typically means the mode you use when compiling for release
which typically means optimizations turned on and debugging information
turned off. It is the opposite of "Debug mode". You are either being
deliberately argumentative or dumb: you should know exactly what I mean by
"Release mode", I didn't invent the term neither did Microsoft.

/Leigh

James Kanze

unread,
Mar 13, 2010, 6:40:32 PM3/13/10
to
On Mar 12, 9:53 pm, Ian Collins <ian-n...@hotmail.com> wrote:
> On 03/13/10 01:21 AM, Leigh Johnston wrote:

> > "Ian Collins" <ian-n...@hotmail.com> wrote:
> >> On 03/12/10 11:36 PM, Leigh Johnston wrote:

> >>> "James Kanze" <james.ka...@gmail.com> wrote:

> >>>> But most of the time, assertions will be active in
> >>>> released code.

> >>> Sigh. What do you mean most of the time? We have been over
> >>> this before. By default assert does nothing in release
> >>> mode which is the way it should be. Release mode = NDEBUG
> >>> = "not debugging" = no op assert.

> >> That depends how you define "release mode"

> >> Most of the software I have released was released with
> >> assertion on and most of the code I use (including my
> >> preferred C++ compiler) has them enabled.

> >> I'd rather have a bug report with a core file than one
> >> without.

> > Release mode asserts are desirable only when a higher degree


> > of defensiveness is required which depends on the
> > application domain in question. There is a reason why assert
> > does nothing when NDEBUG is defined.

> Yes there is, you can turn them off. A lot of applications
> don't. It may depend on the platform, but most Unix
> applications I use (and write) have asserts on; as I said, a
> bug report with a core file than one without. If used
> correctly, asserts trap the unexpected and protect the
> integrity of the application's state. I bet whatever C++
> compiler you use has them turned on.

The standard requires assertions to be active unless they are
explicitly disabled (by defining NDEBUG). The standard also
very explicitly allows including <assert.h> multiple times,
changing whether NDEBUG is defined between the inclusions. The
intent is clearly to allow turning off assertions in a very
controled manner, since you can include <assert.h> multiple
times, and the definition of assert will change each time.

All of the compilers and IDE's that I know (Sun CC, g++, Visual
Studios) have "defaults" set for just playing around. They're
fine if you just want to quickly try something out, but you
wouldn't use them in production code. This is doubtlessly
because there is no one set of defaults that would be
appropriate for all types of production code, so anyone
developing code professionally will read the compiler
documentation, and decide what options are appropriate for his
application.

> Release mode is a nebulous concept; it means different things
> to different people.

Release mode means whatever set of options are used in the code
you release. If at all possible, that will be the same set as
you used to develop the code---I don't like the idea of
releasing code compiled with different options than those I've
tested. There are, however, valid reasons for differences: you
might not what the debugging symbol tables in the released code,
for example. There are even specific cases where you might want
to turn off assertions, at least in critical sections of your
code, and under Windows, it's usually appropriate to catch
SIGABRT, and to intercept structured exceptions, in order to
prevent the silly pop-up window you'll get otherwise.

--
James Kanze

James Kanze

unread,
Mar 13, 2010, 6:48:03 PM3/13/10
to
On Mar 12, 10:10 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:

[...]
> From Microsoft documentation:

Just a note, but Microsoft documentation (like the documentation
of all other compilers) describes the possibilities of the
compiler; it does not define "best practices", nor does it
pretend to.

> The assert macro is typically used to identify logic errors
> during program development by implementing the expression
> argument to evaluate to false only when the program is
> operating incorrectly. After debugging is complete, assertion
> checking can be turned off without modifying the source file
> by defining the identifier NDEBUG. NDEBUG can be defined with
> a /D command-line option or with a #define directive. If
> NDEBUG is defined with #define, the directive must appear
> before ASSERT.H is included.

> Notice the use of the word "typically". My point is that
> *typically* assert is a debugging tool used during the
> development phase and only rarely enabled for released product
> where a higher degree of defensiveness is appropriate.

But there's certainly nothing in what you quoted that would
support that point of view.

> Yes I admit I am a Microsoft fanboy. You are a unix fanboy.
> Fanboys should probably be mostly ignored - but I don't give
> a fuck. :)

Well, I'm not a fanboy. For various reasons, most of my
experience has been on Sun platforms, but I'm currently working
in a mainly Windows environment, and while there are some
definite diffences, basic issues of the development process
are the same.

--
James Kanze

Leigh Johnston

unread,
Mar 13, 2010, 6:48:36 PM3/13/10
to

"James Kanze" <james...@gmail.com> wrote in message

news:247d64ac-62e3-47e0...@q23g2000yqd.googlegroups.com...

> Release mode means whatever set of options are used in the code
> you release. If at all possible, that will be the same set as
> you used to develop the code---I don't like the idea of
> releasing code compiled with different options than those I've
> tested. There are, however, valid reasons for differences: you
> might not what the debugging symbol tables in the released code,
> for example. There are even specific cases where you might want
> to turn off assertions, at least in critical sections of your
> code, and under Windows, it's usually appropriate to catch
> SIGABRT, and to intercept structured exceptions, in order to
> prevent the silly pop-up window you'll get otherwise.
>
> --
> James Kanze

You test your software "releases" and therefore you do use the same "mode"
for testing as for release. You switch to debug mode to understand and fix
the bugs that are reproducible in "release mode". I use "release mode"
during development phase as debug mode usually has unacceptable performance
characteristics.

Trying to prevent "silly pop-up windows" is a stupid thing to say, they are
not "silly".

/Leigh

Leigh Johnston

unread,
Mar 13, 2010, 6:51:23 PM3/13/10
to

"James Kanze" <james...@gmail.com> wrote in message

news:2434b06b-fd65-4107...@e7g2000yqf.googlegroups.com...


> On Mar 12, 10:10 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:
>
> [...]
>> From Microsoft documentation:
>
> Just a note, but Microsoft documentation (like the documentation
> of all other compilers) describes the possibilities of the
> compiler; it does not define "best practices", nor does it
> pretend to.
>
>> The assert macro is typically used to identify logic errors
>> during program development by implementing the expression
>> argument to evaluate to false only when the program is
>> operating incorrectly. After debugging is complete, assertion
>> checking can be turned off without modifying the source file
>> by defining the identifier NDEBUG. NDEBUG can be defined with
>> a /D command-line option or with a #define directive. If
>> NDEBUG is defined with #define, the directive must appear
>> before ASSERT.H is included.
>
>> Notice the use of the word "typically". My point is that
>> *typically* assert is a debugging tool used during the
>> development phase and only rarely enabled for released product
>> where a higher degree of defensiveness is appropriate.
>
> But there's certainly nothing in what you quoted that would
> support that point of view.
>

> --
> James Kanze

You are becoming extremely tiresome, did you not read "The assert macro is
typically used to identify logic errors during program development" and
"After debugging is complete, assertion checking can be turned off".

Get a fucking clue please.

/Leigh

James Kanze

unread,
Mar 13, 2010, 6:55:18 PM3/13/10
to
On Mar 12, 10:17 pm, Ian Collins <ian-n...@hotmail.com> wrote:
> On 03/13/10 11:10 AM, Leigh Johnston wrote:
> > From Microsoft documentation:

[...]


> I don't develop for windows, but isn't it asserts that pop up
> that dialogue box asking if you want to debug or abort (if you
> have VC++ installed) an application when it goes wrong?

That depends on the compiler options: you can chose between that
and a structured exception. If neither is appropriate (usually
the case when developing libraries, since you want to test that
your assertions trigger correctly), then you need to specify no
structured exceptions, explicitly catch SIGABRT, and also tell
the system that you don't want the popup otherwise, by calling
SetErrorMode.

This information is apparently well known in the Microsoft
community, because I hardly had to mention the issue in a
Microsoft forum to get a complete explination. I think you'll
find that a lot of Microsoft programmers are very professional
as well, and are capable of specifying what is appropriate for
their application as well.

--
James Kanze

James Kanze

unread,
Mar 13, 2010, 7:02:08 PM3/13/10
to
On Mar 12, 10:51 pm, Paavo Helde <myfirstn...@osa.pri.ee> wrote:
> "Leigh Johnston" <le...@i42.co.uk> wrote
> innews:z_ydnc0Cn_BHJgfW...@giganews.com:

[...]


> They have the concept of checked iterators,

So does g++. And Sun CC if you use the STLPort.

> which is very similar to asserts, but not implemented via
> assert(). And this feature is on also in Release builds by
> default.

Sort of. Like most modern compilers, Microsoft has a fairly
wide variety of debugging options: NDEBUG is just the tip of the
iceberg. By default (but who's stupid enough to use the
defaults), you get all of them in "debug" mode; some (but not
all) are turned off in release mode, and you can turn on or off
any in either mode (or create a third mode, if that's
appropriate for some reason).

> One has to take extra steps to turn it off. Ok, I understand
> that as this feature affects binary compatibility, they would
> like to to have the same setting in Debug and Release builds
> so that the libraries from different builds can be mixed.

Except that they can't, really. (At least not pre-VC10.0.)
I've encountered a number of problems because of incompatible
debugging options when using std::string. (The other classes
don't seem to be affected.)

> Though, I would consider a debugging feature affecting the
> binary compatibility of libraries as a design failure.

Me too, but realistically... Microsoft does far better than
most in this regard, even if they aren't perfect.

--
James Kanze

Leigh Johnston

unread,
Mar 13, 2010, 7:10:17 PM3/13/10
to

"James Kanze" <james...@gmail.com> wrote in message

news:d44456d6-4f54-4573...@t23g2000yqt.googlegroups.com...

You are confusing crashes (faults) with assertion failures: they are not the
same thing. To change the behaviour of assert use _set_error_mode not
SetErrorMode.

/Leigh

Ian Collins

unread,
Mar 13, 2010, 7:14:02 PM3/13/10
to
On 03/14/10 12:39 PM, Robert Fendt wrote:

> Apart from that, asserts do not always make sense in non-debug
> code anyway. For example, I currently also develop a graphics
> transformation library. If I build it with fully optimisation,
> it becomes faster by a factor of 10-20 (among other things due
> to massive inlining). However, it is more or less _impossible_
> to debug when built fully optimised, so active asserts would not
> do much good anyway.

Don't you have unit tests? Part of my definition of "release" is to
have the code as shipped pass all its unit tests. If your tests are
concise, debugging is straightforward regardless of optimisation.

> By the way, the standard 'assert' macro defined in the standard
> IIRC is explicitely disabled if 'NDEBUG' is defined, and setting
> this preprocessor symbol also disables all sorts of range checks
> etc. in STL containers at least in VC++, if I am not mistaken.
> So in my opinion it could in fact be quite common that asserts
> are inactive in production code, at least if it is
> performance-critical code built with full optimisation.

Those other actions are specific to your compiler and library
combination. But I agree that performance critical code is a good
candidate for disabling asserts.

--
Ian Collins

Leigh Johnston

unread,
Mar 13, 2010, 7:36:20 PM3/13/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:802o9v...@mid.individual.net...

Using performance as a criterion on whether or not to use asserts make the
asserts completely arbitrary and pointless. Like I said earlier you need to
be either extremely defensive or not defensive at all and the degree of
defensiveness depends on the application domain. It is simpler to just
except the truth that "asserts are *mostly* a debugging tool".

/Leigh

Branimir Maksimovic

unread,
Mar 13, 2010, 7:41:10 PM3/13/10
to
On Sun, 14 Mar 2010 00:36:20 -0000
"Leigh Johnston" <le...@i42.co.uk> wrote:
>
> Using performance as a criterion on whether or not to use asserts
> make the asserts completely arbitrary and pointless. Like I said
> earlier you need to be either extremely defensive or not defensive at
> all and the degree of defensiveness depends on the application
> domain. It is simpler to just except the truth that "asserts are
> *mostly* a debugging tool".
>
How's that that C and C++ folks always worry about performance,
while Java folks don;t worry? All my apps run with debug builds
and asserts and are lot faster then Java apps.
If you got the point ;)

Greets

--
http://maxa.homedns.org/

Sometimes online sometimes not


Ian Collins

unread,
Mar 13, 2010, 7:37:46 PM3/13/10
to
On 03/14/10 12:40 PM, James Kanze wrote:
> On Mar 12, 9:53 pm, Ian Collins<ian-n...@hotmail.com> wrote:
>
>> Release mode is a nebulous concept; it means different things
>> to different people.
>
> Release mode means whatever set of options are used in the code
> you release.

Isn't that what I said?

--
Ian Collins

Ian Collins

unread,
Mar 13, 2010, 7:41:19 PM3/13/10
to
On 03/14/10 12:26 PM, James Kanze wrote:
> On Mar 12, 11:21 am, Ian Collins<ian-n...@hotmail.com> wrote:
>> On 03/12/10 11:36 PM, Leigh Johnston wrote:
>
>>> "James Kanze"<james.ka...@gmail.com> wrote:
>
>>>> But most of the time, assertions will be active in released
>>>> code.
>
>>> Sigh. What do you mean most of the time? We have been over
>>> this before. By default assert does nothing in release mode
>>> which is the way it should be. Release mode = NDEBUG = "not
>>> debugging" = no op assert.
>>
>> That depends how you define "release mode"
>
>> Most of the software I have released was released with
>> assertion on and most of the code I use (including my
>> preferred C++ compiler) has them enabled.
>
>> I'd rather have a bug report with a core file than one without.
>
> And I'd rather release the executables that I've tested, rather
> than something else.

Did I say otherwise?

I always run unit tests as part of a build. If the tests fail, the
build fail. The build and test process and the compiler options used
are completely independent.

--
Ian Collins

Robert Fendt

unread,
Mar 14, 2010, 4:50:35 AM3/14/10
to
And thus spake Ian Collins <ian-...@hotmail.com>
Sun, 14 Mar 2010 13:14:02 +1300:

> Don't you have unit tests? Part of my definition of "release" is to
> have the code as shipped pass all its unit tests. If your tests are
> concise, debugging is straightforward regardless of optimisation.

Other than 'check if it crashes', unit tests are not
straight-forward in image morphing code, since you would have to
compare the result against reference images, which differ subtly
if you change e.g. interpolation and filtering settings. This
makes unit testing quite problematic, though I will not say it
cannot be done.

However, I was not talking about testing, but about the lack of
usefulness of running fully optimised code with lots of inlining
in a debugger and hoping to achieve something meaningful. At
least on GCC (which is one of my two development platforms) it's
absolutely useless since the function calls and corresponding
symbols don't even exist in the binary. The situation is
actually a bit less bad on VC++ since it leaves more information
intact even when inlining code. However, what I meant is: you
*test* the optimised build, and if there's a problem, you more
often than not have to go look in the debug build and try to
figure out why.

Regards,
Robert

Chris Gordon-Smith

unread,
Mar 14, 2010, 6:48:25 AM3/14/10
to
James Kanze <james...@gmail.com> wrote:

> Whether exception handling or assertions are more appropriate
> depends on the type of error and the application domain. And
> possibly other considerations as well.
>

I would be interested to know whether there are any guidelines on this. It seems to me
that exceptions are often useful in cases where the program itself has done nothing
wrong, but something unusual has happened in its environment.

For example, 'out of memory', or a network error. If the program's users value
availability, it is probably worth writing exception code to allow the program to
continue, possibly with some degradation of service.

On the other hand, if the error is in the program, there is a lot to be said for
terminating immediately before any more damage is done. This is the approach I am taking
for an Artificial Chemistry simulator I am developing. As it is a research tool there is
no requirement for high availability, and so the simplest thing to do is to use
assertions and terminate at the first sign of trouble.

Another case arises with large systems that do have high availability requirements but
are known to contain occasional logic errors. I recall a case a few years ago in the
'work' part of my life where a global shipment management system had a bug that
occasionally caused it to set shipment charges to zero! No-one could find the bug at
first, but terminating the program was not an option. We decided to adopt a policy of
containment, putting suspect transactions 'in quarantine'. The program was not written in
C++, but perhaps if it had been exception handling could have been used to detect the
condition and deal with it.

Chris Gordon-Smith
www.simsoup.info

Alf P. Steinbach

unread,
Mar 14, 2010, 7:01:39 AM3/14/10
to
* Chris Gordon-Smith:

> James Kanze <james...@gmail.com> wrote:
>
>> Whether exception handling or assertions are more appropriate
>> depends on the type of error and the application domain. And
>> possibly other considerations as well.
>>
>
> I would be interested to know whether there are any guidelines on this.

Sure. That's almost a given. But we're not a point yet where there's even any
consensus about the simplest things.

Consider the C++ standard library's exception hierarchy. I haven't heard about
anyone who use those exception types as their names indicate. Yet very good
brains were involved in forming the standard library.

Consider a language like Python where not only assertions are exceptions, but
some exceptions are used to signal success, like, hey, we exhausted an iterator
as expected, and there are even exceptions called ...Warning. :-)

Personally I think exceptions, as they're commonly expressed in most of today's
languages, are at a too low level of abstraction, sort of like goto.

I like the Eiffel approach to exception handling where exceptions always
indicate failure and the syntax makes it clear what you can do when an exception
occurs: achieve the goal in some other way (e.g. by simple retrying), or fail in
turn. I think this could be particularly clean in C++ where most cleanup can be
achieved via RAII, thus removing that aspect from exception handling. And I once
started a few threads over in [comp.std.c++] suggesting such higher level
syntax, including a few formal definitions, but all that came out of that was
that Dave Harris (I think it was) showed me -- and other readers -- how the
template pattern can express the basic Eiffel exception handling notion.


Cheers,

- Alf

Daniel T.

unread,
Mar 14, 2010, 12:44:17 PM3/14/10
to
Chris Gordon-Smith<use.a...@my.homepage.invalid> wrote:
> James Kanze <james...@gmail.com> wrote:
>
> > Whether exception handling or assertions are more appropriate
> > depends on the type of error and the application domain. And
> > possibly other considerations as well.
>
> I would be interested to know whether there are any guidelines on
> this. It seems to me that exceptions are often useful in cases where
> the program itself has done nothing wrong, but something unusual has
> happened in its environment.

My basic guideline is that a catch should always re-throw, because if
your program can recover from the situation, then it isn't an error.

When writing a function, if a precondition is violated, then an error
has been detected in the calling code, an error that this function
cannot fix (by definition.) Unless you know for a fact that every
program that could possibly use this function should abort whenever a
precondition is violated, without any chance to save data or otherwise
clean up, you should not use 'assert', throw an exception instead.

If a postcondition is violated, then the function was written
incorrectly. Chances are, you didn't write either an assert or exception
to cover such an issue, because if you knew the function wouldn't work,
you would have fixed the code rather than adding code to notify the
caller that your code is broken. Whenever a postcondition violation
takes place, you should fix the code so it can't happen anymore. It
would not be appropriate to leave the bug in and add an assertion or
exception to notify the caller that your code doesn't work.

Leigh Johnston

unread,
Mar 14, 2010, 1:40:22 PM3/14/10
to

"Daniel T." <dani...@earthlink.net> wrote in message
news:daniel_t-6C17AF...@70-3-168-216.pools.spcsdns.net...


> Chris Gordon-Smith<use.a...@my.homepage.invalid> wrote:
>> James Kanze <james...@gmail.com> wrote:
>>
>> > Whether exception handling or assertions are more appropriate
>> > depends on the type of error and the application domain. And
>> > possibly other considerations as well.
>>
>> I would be interested to know whether there are any guidelines on
>> this. It seems to me that exceptions are often useful in cases where
>> the program itself has done nothing wrong, but something unusual has
>> happened in its environment.
>
> My basic guideline is that a catch should always re-throw, because if
> your program can recover from the situation, then it isn't an error.
>

This is a foolish guideline: if you always re-throw then all exceptions will
ultimately result in program termination which is not what exceptions were
designed for. Obviously some errors may be unrecoverable (e.g. allocation
failure) for which program termination is the best outcome but you can also
use exceptions for non-fatal valid error conditions which can be handled at
a different "layer" in your program's design, an example of which might be
invalid user input.

/Leigh

Daniel T.

unread,
Mar 14, 2010, 2:51:41 PM3/14/10
to
"Leigh Johnston" <le...@i42.co.uk> wrote:

Exceptions are for errors, that's what they were designed for. If your
program can handle some particular condition and continue normal
execution, how is that condition an error? The answer is, it isn't.
Invalid user input is a good example of something that should *not*
cause an error in your program, your program should be able to deal with
such input gracefully.

Leigh Johnston

unread,
Mar 14, 2010, 3:00:36 PM3/14/10
to

"Daniel T." <dani...@earthlink.net> wrote in message

news:daniel_t-0D34D7...@70-3-168-216.pools.spcsdns.net...

My point is that you can use exceptions to gracefully handle bad input.
Having an if statement with error code return for every control in your
dialog is not graceful. Exceptions can be used for both fatal errors and
non-fatal valid runtime errors - two types of errors. This is what
exceptions were designed for. OTOH I only have three catches in my entire
codebase and they all rethrow however the GUI framework library I use (MFC)
does use exceptions for bad user input (dialogs). Exceptions allow you to
pass an error through different layers and reduces the need for checking
return values locally. Where does it say that all exceptions must be fatal
errors that require program termination?

/Leigh

Ian Collins

unread,
Mar 14, 2010, 3:03:27 PM3/14/10
to
On 03/15/10 07:51 AM, Daniel T. wrote:
>
> Exceptions are for errors, that's what they were designed for. If your
> program can handle some particular condition and continue normal
> execution, how is that condition an error? The answer is, it isn't.

Nonsense. Just because an error condition can't be handled locally,
doesn't mean it can't be correctly handled elsewhere. For example if an
object fails to construct because a user specifies an absent file,
should the error be handled in the constructor, or passed to a higher layer?

> Invalid user input is a good example of something that should *not*
> cause an error in your program, your program should be able to deal with
> such input gracefully.

True.

--
Ian Collins

Leigh Johnston

unread,
Mar 14, 2010, 3:12:25 PM3/14/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:804qfl...@mid.individual.net...

It is true that such an error should be dealt with gracefully and exceptions
can be used to achieve this. Throwing an exception does not and should not
equal program termination in all cases.

/Leigh

Ian Collins

unread,
Mar 14, 2010, 3:09:41 PM3/14/10
to
On 03/15/10 08:12 AM, Leigh Johnston wrote:

Did I say otherwise?

--
Ian Collins

Leigh Johnston

unread,
Mar 14, 2010, 3:16:48 PM3/14/10
to

"Ian Collins" <ian-...@hotmail.com> wrote in message

news:804qra...@mid.individual.net...

I took exception to you agreeing with a statement that says bad user input
is not an "error". There are different types of errors some fatal some
recoverable. Failure to allocate will probably be a fatal error whilst file
not found might a valid runtime error possibly caused by bad user input.

/Leigh

Chris Gordon-Smith

unread,
Mar 14, 2010, 3:54:30 PM3/14/10
to
Daniel T. <dani...@earthlink.net> wrote:
> Chris Gordon-Smith<use.a...@my.homepage.invalid> wrote:
>> James Kanze <james...@gmail.com> wrote:
>>
>> > Whether exception handling or assertions are more appropriate
>> > depends on the type of error and the application domain. And
>> > possibly other considerations as well.
>>
>> I would be interested to know whether there are any guidelines on
>> this. It seems to me that exceptions are often useful in cases where
>> the program itself has done nothing wrong, but something unusual has
>> happened in its environment.
>
> My basic guideline is that a catch should always re-throw, because if
> your program can recover from the situation, then it isn't an error.
>

Noted, but that's a guideline about how to use exceptions, not about
when to use exceptions and when to use assertions.

Chris Gordon-Smith
www.simsoup.info

Daniel T.

unread,
Mar 14, 2010, 7:41:53 PM3/14/10
to

That's in the part you snipped out. Use assertions when there is a
precondition violation and you know for a fact that every possible
program that may use this function considers it acceptable to abort the
program on error; otherwise use an exception.

Daniel T.

unread,
Mar 14, 2010, 8:33:48 PM3/14/10
to
Ian Collins <ian-...@hotmail.com> wrote:
> On 03/15/10 07:51 AM, Daniel T. wrote:
> >
> > Exceptions are for errors, that's what they were designed for. If
> > your program can handle some particular condition and continue
> > normal execution, how is that condition an error? The answer is, it
> > isn't.
>
> Nonsense. Just because an error condition can't be handled locally,
> doesn't mean it can't be correctly handled elsewhere.

"Something that can't be handled locally" seems to be a rather broad
definition of "error." Much too broad for me?

> For example if an object fails to construct because a user specifies
> an absent file, should the error be handled in the constructor, or
> passed to a higher layer?

I subscribe to the same guidelines that Stroustrup outlines in his book:

Exception handling is a less structured mechanism than local control
structures such as if and for and is often less efficient when an
exception is actually thrown. Therefore, exceptions should be used
only where the more traditional control structures are inelegant or
impossible to use.

...

[Using exceptions as alternate returns] can easily be overused and
lead to obscure code. Whenever reasonable, one should stick to the
"exception handling is error handling" view. When this is done, code
is clearly separated into two categories: ordinary code and
error-handling code. This makes code more comprehensible. ("The C++
Programming Language" section 14.5)

Dealing with bad user input is quite ordinary as I see it.

As Stroustrup says though, the real world is messy and sometimes our
code reflects that. Messy code should not be our goal though.

As for your example, a function that opens a file should have the same
basic error conditions as a find function. In other words, it should
throw an exception only if "object" not found is an *error*. You may ask
how is the function supposed to know if "not found" is an error? The
answer is that if "not found" is not an error, and the function treats
it as such, then the caller should not use the function to do the job.
All this is IMHO of course, we were asked to provide guidelines and this
is the one I use.

I would never write a constructor in such a way that it must
successfully open a file in order to succeed, unless failure to open the
file means that the function creating the object cannot succeed, and on
up the chain.

If your code is littered with empty catch blocks especially, then
something is quite wrong with it as far as I'm concerned.

Kai-Uwe Bux

unread,
Mar 14, 2010, 8:50:03 PM3/14/10
to
Daniel T. wrote:

> Ian Collins <ian-...@hotmail.com> wrote:
>> On 03/15/10 07:51 AM, Daniel T. wrote:
>> >
>> > Exceptions are for errors, that's what they were designed for. If
>> > your program can handle some particular condition and continue
>> > normal execution, how is that condition an error? The answer is, it
>> > isn't.
>>
>> Nonsense. Just because an error condition can't be handled locally,
>> doesn't mean it can't be correctly handled elsewhere.
>
> "Something that can't be handled locally" seems to be a rather broad
> definition of "error." Much too broad for me?

Maybe so, but the question is not whether something that cannot be handled
locally is an error. The question at hand is whether such a condition is a
good candidate for using the try-throw-catch facility of the language. Now
the "cannot be handled locally" seems to indicate that at the point in code
where the condition is first recognized, no reasonable prediction can be
made about the amount of backtracking / stack unwinding needed to deal with
it (that could happen, e.g., inside some library code that is written
without knowledge about client code). In that case, try-throw-catch seems to
be appropriate regardless of whether the detected condition qualifies as an
"error".

Of course, this decision involves a trade-off: try-throw-catch is a wicked
jump across an unknown amount of code, a jump that could take program flow
anywhere. It requires a good deal of care to program in the presence of such
jumps. Nonetheless, sometimes the alternatives are more clumsy, more
convoluted, and less understandable. In that case, I would opt for throwing.

[...]


Best

Kai-Uwe Bux

Daniel T.

unread,
Mar 14, 2010, 10:03:33 PM3/14/10
to
"Leigh Johnston" <le...@i42.co.uk> wrote:
> "Daniel T." <dani...@earthlink.net> wrote:
>
> > Exceptions are for errors, that's what they were designed for. If
> > your program can handle some particular condition and continue
> > normal execution, how is that condition an error? The answer is, it
> > isn't. Invalid user input is a good example of something that should
> > *not* cause an error in your program, your program should be able to
> > deal with such input gracefully.
>
> My point is that you can use exceptions to gracefully handle bad
> input. Having an if statement with error code return for every control
> in your dialog is not graceful.

In my experience, having a slew of catch blocks each dealing with a
different type of user input is even less graceful.

> Exceptions can be used for both fatal errors and non-fatal valid
> runtime errors - two types of errors.

The fundamental difference between us, I think, is how we define
"error." I define it as something the program cannot recover from. When
the design says, "If the user does X, then the program must to Y," I
don't call it an error when the user does X. If the design requires that
condition A must pertain at point B, and condition A does not pertain at
point B; I call *that* an error.

Ian Collins

unread,
Mar 14, 2010, 10:46:43 PM3/14/10
to
On 03/15/10 03:03 PM, Daniel T. wrote:
> "Leigh Johnston"<le...@i42.co.uk> wrote:
>> "Daniel T."<dani...@earthlink.net> wrote:
>>
>>> Exceptions are for errors, that's what they were designed for. If
>>> your program can handle some particular condition and continue
>>> normal execution, how is that condition an error? The answer is, it
>>> isn't. Invalid user input is a good example of something that should
>>> *not* cause an error in your program, your program should be able to
>>> deal with such input gracefully.
>>
>> My point is that you can use exceptions to gracefully handle bad
>> input. Having an if statement with error code return for every control
>> in your dialog is not graceful.
>
> In my experience, having a slew of catch blocks each dealing with a
> different type of user input is even less graceful.

That's a pretty rare circumstance, I've certainly never seen it. A more
common scenario would be:

try {
doSomething();
doAnotherSomething();
doSomethingElse();
}
catch( const std::runtime_error& e ) {
dieOrRecover();
}

As an alternative to checking the return of all calls. This approach
tends to be both clearer (less clutter, al clean up in one place) and
more efficient (no tests after ever call that can fail).

>> Exceptions can be used for both fatal errors and non-fatal valid
>> runtime errors - two types of errors.
>
> The fundamental difference between us, I think, is how we define
> "error." I define it as something the program cannot recover from. When
> the design says, "If the user does X, then the program must to Y," I
> don't call it an error when the user does X. If the design requires that
> condition A must pertain at point B, and condition A does not pertain at
> point B; I call *that* an error.

Exceptions are for exceptional circumstances. If something that
shouldn't fail fails, that's and exceptional circumstance. That's why I
mentioned file opening failing, if the file should be there, throw if it
isn't. If it's expected to sometimes not be there, deal with it on the
spot.

If something is guaranteed not to happen, assert if it does!

--
Ian Collins

Michael Doubez

unread,
Mar 15, 2010, 4:24:02 AM3/15/10
to
On 13 mar, 00:13, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Ian Collins" <ian-n...@hotmail.com> wrote in message
>
> news:7vvvj8...@mid.individual.net...
>
>
>
> > On 03/13/10 11:41 AM, Leigh Johnston wrote:
> >> "Ian Collins" <ian-n...@hotmail.com> wrote:
>
> >>> If something unexpected happens and the compiler's internal state
> >>> becomes corrupt, do you want it to generate bad code, fall in a heap
> >>> or bail with an assertion failure? As both a user and a developer, I
> >>> know which one I'd prefer.
>
> >> I misunderstood. Yes I agree, I already said there are exceptions where
> >> a higher degree of defensiveness may be required and a compiler might be
> >> such an exception as it can be used to compile software which might
> >> itself require a higher degree of defensiveness. This doesn't change the
> >> fact that assert is primarily a debugging aid.
>
> > Ah, good we are on the same wavelength at last.
>
> > I still disagree with assert being primarily a debugging aid.  Unit tests
> > should be the debugging tool, asserts are the safety net for those
> > unexpected events that can't be handled by the application's logic.
>
> > I may be biased coming from an embedded background, but one of the first
> > lessons an embedded developer learns is to expect the unexpected and
> > defend against it.  A typical real example was a driver I wrote for a
> > serial device; according the data sheet, it was impossible for the data
> > read interrupt to fire with an empty input buffer.  So I added an
> > assertion in the interrupt handler.  Sure enough, in a customer site, the
> > product rebooted.  The log showed that assert had triggered.
>
> Actually I think embedded software is one of the exceptions where a higher
> degree of defensiveness is required (especially where safety is a concern)
> and a reboot is usually the best outcome for unexpected state.  On the other
> hand I have worked in the mobile phone industry and from what I can recall
> we didn't use release mode asserts much.

I also have an embedded software background but now I work in finance
and the rules are more or less the same: they prefer an error than a
program in an inconsistent state that will report erroneous value or
state to customer (I expect customers get upset when their algorithm
buy/sell at the wrong price).

The only difference is that they prefer to work in degraded mode (mark
a state inconsistent) rather than reboot the program when possible but
only because other mechanisms are used. Continuation of service is
important but correctness is generally preferred.

Well, it is an old argument.

Renaming NDEBUG into NASSERT would have help ... perhaps.

--
Michael

Michael Doubez

unread,
Mar 15, 2010, 4:32:49 AM3/15/10
to
On 12 mar, 15:38, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Michael Doubez" <michael.dou...@free.fr> wrote in message
>
> news:f6db8690-71d0-4cbf...@g26g2000yqn.googlegroups.com...

>
>
>
> > On 12 mar, 13:21, "Leigh Johnston" <le...@i42.co.uk> wrote:
> >> "Ian Collins" <ian-n...@hotmail.com> wrote in message
>
> >>news:7vuml0...@mid.individual.net...

>
> >> > On 03/12/10 11:36 PM, Leigh Johnston wrote:
> >> >> "James Kanze" <james.ka...@gmail.com> wrote:
>
> >> >>> But most of the time, assertions will be active in released
> >> >>> code.
>
> >> >> Sigh. What do you mean most of the time? We have been over this
> >> >> before.
> >> >> By default assert does nothing in release mode which is the way it
> >> >> should be. Release mode = NDEBUG = "not debugging" = no op assert.
>
> >> > That depends how you define "release mode"
>
> >> > Most of the software I have released was released with assertion on and
> >> > most of the code I use (including my preferred C++ compiler) has them
> >> > enabled.
>
> >> > I'd rather have a bug report with a core file than one without.
>
> >> > --
> >> > Ian Collins
>
> >> Release mode asserts are desirable only when a higher degree of
> >> defensiveness is required which depends on the application domain in
> >> question.
>
> > I would say the definition is the contrary: a program without assert
> > is possible only when a inconsistent state of the program is
> > admissible.
>
> Nonsense, either be extremely defensive or not defensive at all, somewhere
> inbetween is pointless and an assert before/after very state changing
> function is overkill for lots of application domains.

When you are carrying human lives (and I include in that the lives of
people, their money and the product of their work), could you give me
and adequate level for not-overkill ?

When the state don't change so often, an assert is a little price,
helps to understand the code and provides a level of defense.


> > I would say it is only possible for programs that don't modify a state
> > (such as the program ls) and for which you don't care about locating
> > bug on the user's plateform.
>
> >>  There is a reason why assert does nothing when NDEBUG is defined.
>
> > Because the C standard dictates that when NDEBUG is defined, the
> > assert macro shall expand to nothing.
>
> > NDEBUG has no other effect or meaning whatsoever.
>
> > But I find relevant that the assert() are activated by default and it
> > is a defines that disables them. If assert() was only a debug feature,
> > I would have expected the reverse: DEBUG enabling asserts.
>
> assert is a debug feature, the NDEBUG means "not debugging" and when we are
> "not debugging" assert does nothing.

From the standard's point of view, NDEBUG means "assert have been
removed".

If you program by contract, it means: I run wihtout checking the terms
of the contract; which, as in real life, is fine until there i6s a
problem and you end up with only your pant (and a spare shirt).

--
Michael

Nick Keighley

unread,
Mar 15, 2010, 6:04:02 AM3/15/10
to
On 12 Mar, 23:00, Ian Collins <ian-n...@hotmail.com> wrote:

> I still disagree with assert being primarily a debugging aid.  Unit
> tests should be the debugging tool, asserts are the safety net for those
> unexpected events that can't be handled by the application's logic.
>
> I may be biased coming from an embedded background, but one of the first
> lessons an embedded developer learns is to expect the unexpected and
> defend against it.

I was taught in my OS course "that anything that can happen, will
happen". This transferred nicely to RT programming. I too leave the
assert()s on. I may disable more expensive one (assert
(tree_is_vallid(tree)). but the cheap ones stay. How can you allow a
program to run on in an undefined state?

Nick Keighley

unread,
Mar 15, 2010, 6:20:24 AM3/15/10
to
On 14 Mar, 16:44, "Daniel T." <danie...@earthlink.net> wrote:
> Chris Gordon-Smith<use.addr...@my.homepage.invalid> wrote:
> > James Kanze <james.ka...@gmail.com> wrote:

> > > Whether exception handling or assertions are more appropriate
> > > depends on the type of error and the application domain.  And
> > > possibly other considerations as well.
>
> > I would be interested to know whether there are any guidelines on
> > this. It seems to me that exceptions are often useful in cases where
> > the program itself has done nothing wrong, but something unusual has
> > happened in its environment.
>
> My basic guideline is that a catch should always re-throw, because if
> your program can recover from the situation, then it isn't an error.

this seems like a matter of how you define things. It might be an
error in some subprogram that doesn't affect the system as a whole. In
high availability transaction oriented things it might be sensible to
abort the current "transaction" and continue. Telecomms stuff seems
well suited to this.

I've written (noddy) parsers where exceptions seem a fine way of
bailing out of a deeply nested RDP.

I've written C and Python versions of simple socket drivers. The
python looks much nicer because the error handling is separate.


> When writing a function, if a precondition is violated, then an error
> has been detected in the calling code, an error that this function
> cannot fix (by definition.) Unless you know for a fact that every
> program that could possibly use this function should abort whenever a
> precondition is violated, without any chance to save data or otherwise
> clean up, you should not use 'assert', throw an exception instead.

yes. I've wrappered Win-32 calls so they threw if an error occurred.
And in some cases I handle the error rather than terminate.

> If a postcondition is violated, then the function was written
> incorrectly. Chances are, you didn't write either an assert or exception
> to cover such an issue, because if you knew the function wouldn't work,
> you would have fixed the code rather than adding code to notify the
> caller that your code is broken. Whenever a postcondition violation
> takes place, you should fix the code so it can't happen anymore. It
> would not be appropriate to leave the bug in and add an assertion or
> exception to notify the caller that your code doesn't work.

this is why linux never panics


--
Nick Keighley


Leigh Johnston

unread,
Mar 15, 2010, 6:38:41 AM3/15/10
to

"Daniel T." <dani...@earthlink.net> wrote in message

news:daniel_t-C50B1D...@70-3-168-216.pools.spcsdns.net...

Five words: you are full of shit. Exceptions are not for just fatal
programming errors that terminate the program and Stroustrup agrees with
this. Conversation over.

/Leigh

Leigh Johnston

unread,
Mar 15, 2010, 6:40:26 AM3/15/10
to

"Daniel T." <dani...@earthlink.net> wrote in message

news:daniel_t-0BB794...@70-3-168-216.pools.spcsdns.net...

You said always rethrow your exceptions which means if you follow your
advice there is no difference between asserts and exceptions (assuming you
are one of the retards who say that exceptions should always be enabled).

/Leigh

Leigh Johnston

unread,
Mar 15, 2010, 6:43:13 AM3/15/10
to

"Leigh Johnston" <le...@i42.co.uk> wrote in message
news:M5adnQiyssUOkwPW...@giganews.com...

Correction: "who say that asserts should always be enabled". :)

/Leigh

Leigh Johnston

unread,
Mar 15, 2010, 7:34:52 AM3/15/10
to

"Michael Doubez" <michael...@free.fr> wrote in message
news:eeee5426-75fd-4459...@g19g2000yqe.googlegroups.com...

This sounds like a nightmare and completely wrong: if you have code that can
determine that something is seriously wrong then you should be using release
mode asserts and terminate the program rather than trying to continue in
some "degraded mode". The alternative is to have no release mode asserts
whatsoever and perhaps rely on a select few exceptions in core software
components (e.g. a container checking for bounds overrun) and rely on
program terminating (or crashing) in a predictable way... :)

/Leigh

Michael Doubez

unread,
Mar 15, 2010, 8:58:09 AM3/15/10
to
On 15 mar, 12:34, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Michael Doubez" <michael.dou...@free.fr> wrote in message

You can also isolate a functionality or some handling of the data.

In this specific case, some precondition of the program (such as
entries from a data flow that *should* be unique) are not respected.
This would normally lead to a logic error for the associated parts
which rely on this precondition. In this case, the program raises an
alert (a big one), offending data is discarded and further use of the
state associated to it is marked as inconsistent.

Here, it is better than trying to explain to the customer that it is
not your fault but the data provider which didn't respect the specs or
that bugs to happen and that's the way things are.

--
Michael

Leigh Johnston

unread,
Mar 15, 2010, 9:11:24 AM3/15/10
to

"Michael Doubez" <michael...@free.fr> wrote in message

news:d06b1628-8af5-4e47...@f8g2000yqn.googlegroups.com...

I agree it is possible to discard data and abort some subsystem without
terminating the entire process, this is just normal error handling and is
best handled with exceptions of course.

/Leigh

Leigh Johnston

unread,
Mar 15, 2010, 9:15:20 AM3/15/10
to

"Leigh Johnston" <le...@i42.co.uk> wrote in message

news:V5qdnYeQE5hgrAPW...@giganews.com...

However discarding bad data and associated objects is not the same as trying
to continue because of some bug in the code. Bugs in code should result in
either an abort (due to an assert) or an exception which results in program
termination. The correct answer to your problem is better data validation
and normal error handling (through use of exceptions perhaps).

/Leigh

Nick Keighley

unread,
Mar 15, 2010, 10:29:07 AM3/15/10
to
On 15 Mar, 10:40, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Daniel T." <danie...@earthlink.net> wrote in message
> news:daniel_t-0BB794...@70-3-168-216.pools.spcsdns.net...
> > Chris Gordon-Smith <use.addr...@my.homepage.invalid> wrote:
> >> Daniel T. <danie...@earthlink.net> wrote:

<snip>

> >> > My basic guideline is that a catch should always re-throw, because
> >> > if your program can recover from the situation, then it isn't an
> >> > error.
>
> >> Noted, but that's a guideline about how to use exceptions, not about
> >> when to use exceptions and when to use assertions.
>
> > That's in the part you snipped out. Use assertions when there is a
> > precondition violation and you know for a fact that every possible
> > program that may use this function considers it acceptable to abort the
> > program on error; otherwise use an exception.
>
> You said always rethrow your exceptions which means if you follow your
> advice there is no difference between asserts and exceptions

exceptions invoke all the DTORs and /they/ could be quite clever.

Yannick Tremblay

unread,
Mar 15, 2010, 10:33:43 AM3/15/10
to
In article <20100314095...@vulcan.local>,
Robert Fendt <no....@local.local> wrote:
>And thus spake Ian Collins <ian-...@hotmail.com>
>Sun, 14 Mar 2010 13:14:02 +1300:
>
>> Don't you have unit tests? Part of my definition of "release" is to
>> have the code as shipped pass all its unit tests. If your tests are
>> concise, debugging is straightforward regardless of optimisation.
>
>Other than 'check if it crashes', unit tests are not
>straight-forward in image morphing code, since you would have to
>compare the result against reference images, which differ subtly
>if you change e.g. interpolation and filtering settings. This
>makes unit testing quite problematic, though I will not say it
>cannot be done.

Hmm, you appear to have a different definition of unit tests than I
have: in my case: tests a unit with a unit being the smallest testable
part of an application.

So although it might be difficult to "unit test" that complete process
of having a user picking a random image, randomly changing setting and
then figuring out if the result is correct automatically, I do not see
image morphing code as different in the one should be able to write
low level, "small unit" tests that test that the "small unit" (e.g. a
method) does the job it is designed to do correctly.

>However, I was not talking about testing, but about the lack of
>usefulness of running fully optimised code with lots of inlining
>in a debugger and hoping to achieve something meaningful. At
>least on GCC (which is one of my two development platforms) it's
>absolutely useless since the function calls and corresponding
>symbols don't even exist in the binary. The situation is
>actually a bit less bad on VC++ since it leaves more information
>intact even when inlining code. However, what I meant is: you
>*test* the optimised build, and if there's a problem, you more
>often than not have to go look in the debug build and try to
>figure out why.

Wait a minute, you are confusing several different concepts here:

1- assert
2- optimisation
3- debug symbols

In g++:

1- assert: -DNDEBUG will disable the asserts. If the asserts are
enabled, triggering an assert will make the program stop immediately
(possibly with a core dump that can be later use for debugging but
stopping the program from running is only very weakly related to
debugging. Its most fundamental effect is not to let the program
continue after the point where the assertion has failed. Start or not
starting a debugger afterwards is purely secondary.

2- Optimisation: -O* and a lot of other specific code. This is purely
instructions to the compiler that it should make effort to generate
code that is more optimal. It may also specify what type of
optimisation are desired or what is allowed and disallowed.

3- debug sympols: -g, -g*: this tells the compiler to include
debugging symbol in the binary. This is totally unrelated with the
previous two. g++ is perfectly able to generate code with g++ -O3
-ggdb. The output of which will have debugging symbols and you will
be able to step through it with a debugger. You might have to learn
things in the process 'though because the generated optimised code
might differ from what you originally wrote.


Yannick

Leigh Johnston

unread,
Mar 15, 2010, 10:44:44 AM3/15/10
to

"Nick Keighley" <nick_keigh...@hotmail.com> wrote in message
news:197841d6-12c5-4e43...@19g2000yqu.googlegroups.com...

Yes I know all about RAII but that doesn't stop std::terminate from being
called if exceptions are always re-thrown, something which I do not agree
with as a general guideline.

/Leigh

Daniel T.

unread,
Mar 15, 2010, 10:49:07 AM3/15/10
to
"Leigh Johnston" <le...@i42.co.uk> wrote:

> Five words: you are full of shit.

Now *that's* a powerful argument!

Leigh Johnston

unread,
Mar 15, 2010, 10:53:36 AM3/15/10
to

"Daniel T." <dani...@earthlink.net> wrote in message

news:daniel_t-9F0E0F...@70-3-168-216.pools.spcsdns.net...


> "Leigh Johnston" <le...@i42.co.uk> wrote:
>
>> Five words: you are full of shit.
>
> Now *that's* a powerful argument!

My choice of language reflects the fact that this newsgroup is rather
informal and is full of posts from idiots.

/Leigh

Daniel T.

unread,
Mar 15, 2010, 10:54:51 AM3/15/10
to
Ian Collins <ian-...@hotmail.com> wrote:
> On 03/15/10 03:03 PM, Daniel T. wrote:
>
> > I define [an error] as something the program cannot recover from.

> > When the design says, "If the user does X, then the program must to
> > Y," I don't call it an error when the user does X. If the design
> > requires that condition A must pertain at point B, and condition A
> > does not pertain at point B; I call *that* an error.
>
> Exceptions are for exceptional circumstances. If something that
> shouldn't fail fails, that's and exceptional circumstance. That's why
> I mentioned file opening failing, if the file should be there, throw
> if it isn't. If it's expected to sometimes not be there, deal with it
> on the spot.

The above is essentially what I have been saying all along. How are our
positions different again?

> If something is guaranteed not to happen, assert if it does!

I would add that you only should use the assert macro if you know for a
fact that every program that might ever use the function in question
will find aborting without cleanup an acceptable alternative.

Leigh Johnston

unread,
Mar 15, 2010, 11:02:01 AM3/15/10
to

"Daniel T." <dani...@earthlink.net> wrote in message

news:daniel_t-32E7DF...@70-3-168-216.pools.spcsdns.net...


> Ian Collins <ian-...@hotmail.com> wrote:
>> On 03/15/10 03:03 PM, Daniel T. wrote:
>>
>> > I define [an error] as something the program cannot recover from.
>> > When the design says, "If the user does X, then the program must to
>> > Y," I don't call it an error when the user does X. If the design
>> > requires that condition A must pertain at point B, and condition A
>> > does not pertain at point B; I call *that* an error.
>>
>> Exceptions are for exceptional circumstances. If something that
>> shouldn't fail fails, that's and exceptional circumstance. That's why
>> I mentioned file opening failing, if the file should be there, throw
>> if it isn't. If it's expected to sometimes not be there, deal with it
>> on the spot.
>
> The above is essentially what I have been saying all along. How are our
> positions different again?

I take issue with your definition of what is "exceptional". Invalid user
input can be described as "exceptional". Exceptions are not just for
program terminating fatal errors. Exceptions reduce the amount of ugly if
statements checking ugly return values and having to propagate such error
conditions manually up through the layers of your design.

/Leigh

Daniel T.

unread,
Mar 15, 2010, 11:25:53 AM3/15/10
to
Nick Keighley <nick_keigh...@hotmail.com> wrote:
> On 14 Mar, 16:44, "Daniel T." <danie...@earthlink.net> wrote:
> > Chris Gordon-Smith<use.addr...@my.homepage.invalid> wrote:
> > > James Kanze <james.ka...@gmail.com> wrote:
>
> > > > Whether exception handling or assertions are more appropriate
> > > > depends on the type of error and the application domain.  And
> > > > possibly other considerations as well.
> >
> > > I would be interested to know whether there are any guidelines on
> > > this. It seems to me that exceptions are often useful in cases
> > > where the program itself has done nothing wrong, but something
> > > unusual has happened in its environment.
> >
> > My basic guideline is that a catch should always re-throw, because
> > if your program can recover from the situation, then it isn't an
> > error.
>
> this seems like a matter of how you define things. It might be an
> error in some subprogram that doesn't affect the system as a whole. In
> high availability transaction oriented things it might be sensible to
> abort the current "transaction" and continue. Telecomms stuff seems
> well suited to this.

True, and my domain probably influences my definitions (as well it
should.) In my domain, (games and educational software for 8-12 y.o.
girls,) the design is such that the user *can't* give invalid input.
Also, we have specific resources that we *must* keep within (a failed
memory allocation for example means the code needs to be rewritten,) and
the only files that we open have to be there or the program must abort.

Vladimir Jovic

unread,
Mar 15, 2010, 12:35:11 PM3/15/10
to
Leigh Johnston wrote:
> My choice of language reflects the fact that this newsgroup is rather
> informal and is full of posts from idiots.

Not true. Your choice of language shows what your parents thought you.

The fact that the NG is informal and who posts to it is IMO irrelevant.

Leigh Johnston

unread,
Mar 15, 2010, 12:40:31 PM3/15/10
to

"Vladimir Jovic" <vlada...@gmail.com> wrote in message
news:hnlnen$9c4$1...@news.albasani.net...


> Leigh Johnston wrote:
>> My choice of language reflects the fact that this newsgroup is rather
>> informal and is full of posts from idiots.
>
> Not true. Your choice of language shows what your parents thought you.

IMO your choice of language does not stop evolving when you reach a certain
age, but continues and is affected by the environment (people around you) at
the time.

>
> The fact that the NG is informal and who posts to it is IMO irrelevant.

Posting by idiots is not irrelevant when you have to waste time replying to
said posts correcting stupid opinions such as "you must re-throw all
exceptions and have your program terminate". If you don't do this then
newbies are likely to learn bad practices.

/Leigh

Leigh Johnston

unread,
Mar 15, 2010, 12:46:46 PM3/15/10
to

"Leigh Johnston" <le...@i42.co.uk> wrote in message

news:S5GdnQZki76c_gPW...@giganews.com...

I have come to the conclusion that this newsgroup is mostly a pissing
contest.

/Leigh

Yannick Tremblay

unread,
Mar 15, 2010, 1:19:05 PM3/15/10
to
In article <804qra...@mid.individual.net>,
Ian Collins <ian-...@hotmail.com> wrote:

>On 03/15/10 08:12 AM, Leigh Johnston wrote:
>> "Ian Collins" <ian-...@hotmail.com> wrote:
>>> On 03/15/10 07:51 AM, Daniel T. wrote:
>>>>
>>>> Exceptions are for errors, that's what they were designed for. If your
>>>> program can handle some particular condition and continue normal
>>>> execution, how is that condition an error? The answer is, it isn't.
>>>
>>> Nonsense. Just because an error condition can't be handled locally,
>>> doesn't mean it can't be correctly handled elsewhere. For example if

>>> an object fails to construct because a user specifies an absent file,
>>> should the error be handled in the constructor, or passed to a higher
>>> layer?
>>>
>>>> Invalid user input is a good example of something that should *not*
>>>> cause an error in your program, your program should be able to deal with
>>>> such input gracefully.
>>>
>>> True.
>>
>> It is true that such an error should be dealt with gracefully and
>> exceptions can be used to achieve this. Throwing an exception does not
>> and should not equal program termination in all cases.
>
>Did I say otherwise?

Euh, maybe my reading skill are poor but:

Quote from Ian Collins in this thread:

"My basic guideline is that a catch should always re-throw, because if
your program can recover from the situation, then it isn't an error."

"Exceptions are for errors, that's what they were designed for. If your
program can handle some particular condition an error? The answer is,
it isn't."

"The fundamental difference between us, I think, is how we define
"error." I define it as something the program cannot recover from."

Sounds to me that you have been arguing that only fatal errors should
ever throw and that a program should never ever attempt to recover
from it because if "it was possible to recover, it isn't an error".

I am sorry but it does sound like you were arguing that exceptions
must always terminate the program and the code should only ever throw
for totally irrecoverable conditions and only use status return code
for anything else. I, for one, disagree with this position

Yannick

peter koch

unread,
Mar 15, 2010, 1:59:42 PM3/15/10
to
On 15 Mar., 15:54, "Daniel T." <danie...@earthlink.net> wrote:

> Ian Collins <ian-n...@hotmail.com> wrote:
> > On 03/15/10 03:03 PM, Daniel T. wrote:
>
> > > I define [an error] as something the program cannot recover from.
> > > When the design says, "If the user does X, then the program must to
> > > Y," I don't call it an error when the user does X. If the design
> > > requires that condition A must pertain at point B, and condition A
> > > does not pertain at point B; I call *that* an error.
>
> > Exceptions are for exceptional circumstances.  If something that
> > shouldn't fail fails, that's and exceptional circumstance.  That's why
> > I mentioned file opening failing, if the file should be there, throw
> > if it isn't.  If it's expected to sometimes not be there, deal with it
> > on the spot.
>
> The above is essentially what I have been saying all along. How are our
> positions different again?

In your belief that an exception should always lead to the termination
of the program and that detetion of a a programming error should lead
to an exeption. This is absolutely silly.


>
> > If something is guaranteed not to happen, assert if it does!
>
> I would add that you only should use the assert macro if you know for a
> fact that every program that might ever use the function in question
> will find aborting without cleanup an acceptable alternative.

And what kind of program would not want to abort without cleaning up?
In general you would want to do as little as possible after a program
violation has been detected. About the only reasonable thing to do is
asking the backup program to take over, but that should happen
automatically anyway.
The one exeption to this I can think of is game-programming.

/Peter

peter koch

unread,
Mar 15, 2010, 2:02:06 PM3/15/10
to
On 15 Mar., 18:19, ytrem...@nyx.nyx.net (Yannick Tremblay) wrote:
> In article <804qraFf5...@mid.individual.net>,

> Ian Collins  <ian-n...@hotmail.com> wrote:
>
>
>
>
>
> >On 03/15/10 08:12 AM, Leigh Johnston wrote:
[snip]

I believe that quote is from Daniel T. I can't imagine Ian Collins
claiming that.

/Peter

peter koch

unread,
Mar 15, 2010, 2:10:59 PM3/15/10
to
On 15 Mar., 11:43, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Leigh Johnston" <le...@i42.co.uk> wrote in message
>
> news:M5adnQiyssUOkwPW...@giganews.com...
>
>
>
>
>
>
>
> > "Daniel T." <danie...@earthlink.net> wrote in message
> >news:daniel_t-0BB794...@70-3-168-216.pools.spcsdns.net...

> >> Chris Gordon-Smith <use.addr...@my.homepage.invalid> wrote:
> >>> Daniel T. <danie...@earthlink.net> wrote:
> >>> > Chris Gordon-Smith<use.addr...@my.homepage.invalid> wrote:
> >>> > > James Kanze <james.ka...@gmail.com> wrote:
>
> >>> > > > Whether exception handling or assertions are more appropriate
> >>> > > > depends on the type of error and the application domain.  And
> >>> > > > possibly other considerations as well.
>
> >>> > > I would be interested to know whether there are any guidelines on
> >>> > > this. It seems to me that exceptions are often useful in cases
> >>> > > where the program itself has done nothing wrong, but something
> >>> > > unusual has happened in its environment.
>
> >>> > My basic guideline is that a catch should always re-throw, because
> >>> > if your program can recover from the situation, then it isn't an
> >>> > error.
>
> >>> Noted, but that's a guideline about how to use exceptions, not about
> >>> when to use exceptions and when to use assertions.
>
> >> That's in the part you snipped out. Use assertions when there is a
> >> precondition violation and you know for a fact that every possible
> >> program that may use this function considers it acceptable to abort the
> >> program on error; otherwise use an exception.
>
> > You said always rethrow your exceptions which means if you follow your
> > advice there is no difference between asserts and exceptions (assuming you
> > are one of the retards who say that exceptions should always be enabled).
>
> Correction: "who say that asserts should always be enabled". :)

But always enabling assertions is a good idea. I see no reason
whatsoever to turn assertions off unless you have a piece of code that
gets to slow when enabling the assertions.
Personally, I used to have more levels of assertions. Asserts that
make O(1) algorithms O(n) (or worse) were disabled in release-code
(and often also in test-code: it was typically only enabled after
changing code that might affect the module), but normal asserts were
normally allowed to stay unless a performance test told us not to.

/Peter

Leigh Johnston

unread,
Mar 15, 2010, 2:38:24 PM3/15/10
to

"peter koch" <peter.ko...@gmail.com> wrote in message
news:30a9cb15-752d-4306...@g26g2000yqn.googlegroups.com...

I hate repeating myself but:

Using performance as a criterion on whether or not to use asserts make the
asserts completely arbitrary and pointless. Like I said earlier you need to
be either extremely defensive or not defensive at all and the degree of
defensiveness depends on the application domain. It is simpler to just
except the truth that "asserts are *mostly* a debugging tool".

/Leigh

Ian Collins

unread,
Mar 15, 2010, 4:35:51 PM3/15/10
to

Thanks! Yes, the quote was form Daniel T and not me.

--
Ian Collins

James Kanze

unread,
Mar 15, 2010, 6:23:47 PM3/15/10
to
On Mar 12, 11:13 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "Ian Collins" <ian-n...@hotmail.com> wrote in message

[...]


> Actually I think embedded software is one of the exceptions
> where a higher degree of defensiveness is required (especially
> where safety is a concern) and a reboot is usually the best
> outcome for unexpected state. On the other hand I have worked
> in the mobile phone industry and from what I can recall we
> didn't use release mode asserts much.

I think it depends on where your program is situated. If it's
in the phone itself, I can see not using asserts much, except
maybe in a very few of the critical parts. A mobile phone,
today, is pretty much the same thing as a games console:-). But
the software I've seen on the server side definitely makes
extensive use of asserts; if anything goes wrong, you want to
fail brutally, so that the backup systems can detect the failure
and take over.

--
James Kanze

James Kanze

unread,
Mar 15, 2010, 6:35:02 PM3/15/10
to
On Mar 14, 12:10 am, "Leigh Johnston" <le...@i42.co.uk> wrote:
> "James Kanze" <james.ka...@gmail.com> wrote in message

[...]
> > That depends on the compiler options: you can chose between that
> > and a structured exception. If neither is appropriate (usually
> > the case when developing libraries, since you want to test that
> > your assertions trigger correctly), then you need to specify no
> > structured exceptions, explicitly catch SIGABRT, and also tell
> > the system that you don't want the popup otherwise, by calling
> > SetErrorMode.

> > This information is apparently well known in the Microsoft
> > community, because I hardly had to mention the issue in a
> > Microsoft forum to get a complete explination. I think you'll
> > find that a lot of Microsoft programmers are very professional
> > as well, and are capable of specifying what is appropriate for
> > their application as well.

> You are confusing crashes (faults) with assertion failures:
> they are not the same thing. To change the behaviour of
> assert use _set_error_mode not SetErrorMode.

I didn't know about that one. Still, catching SIGABRT does seem
to have worked, at least in this one particular case.
(According to the standard, an assertion failure is required to
result in a SIGABRT signal. On a lot of systems, signals are
also what is used to indicate other types of crashes: segment
violations and such.)

--
James Kanze

James Kanze

unread,
Mar 15, 2010, 6:38:15 PM3/15/10
to
On Mar 14, 12:37 am, Ian Collins <ian-n...@hotmail.com> wrote:
> On 03/14/10 12:40 PM, James Kanze wrote:

> > On Mar 12, 9:53 pm, Ian Collins<ian-n...@hotmail.com> wrote:

> >> Release mode is a nebulous concept; it means different things
> >> to different people.

> > Release mode means whatever set of options are used in the code
> > you release.

> Isn't that what I said?

I think we pretty much agree on this issue. But I don't see
anything "nebulous" about release mode. And it's the same mode
I use when I test my code, because I don't believe in releasing
untested code. (Something I'm pretty sure you agree with as
well.)

--
James Kanze

Ian Collins

unread,
Mar 15, 2010, 6:38:50 PM3/15/10
to

My example was from the infrastructure side of mobile (or fixed line)
networks. The device in question can shut down and exchange or base
station, so it must "fail brutally" if an inconsistent state is detected.

--
Ian Collins

James Kanze

unread,
Mar 15, 2010, 6:41:44 PM3/15/10
to
On Mar 14, 12:41 am, Ian Collins <ian-n...@hotmail.com> wrote:
> On 03/14/10 12:26 PM, James Kanze wrote:
> > On Mar 12, 11:21 am, Ian Collins<ian-n...@hotmail.com> wrote:
> >> On 03/12/10 11:36 PM, Leigh Johnston wrote:

> >>> "James Kanze"<james.ka...@gmail.com> wrote:

> >>>> But most of the time, assertions will be active in released
> >>>> code.

> >>> Sigh. What do you mean most of the time? We have been over
> >>> this before. By default assert does nothing in release mode
> >>> which is the way it should be. Release mode = NDEBUG = "not
> >>> debugging" = no op assert.

> >> That depends how you define "release mode"

> >> Most of the software I have released was released with
> >> assertion on and most of the code I use (including my
> >> preferred C++ compiler) has them enabled.

> >> I'd rather have a bug report with a core file than one
> >> without.

> > And I'd rather release the executables that I've tested, rather
> > than something else.
>
> Did I say otherwise?

No. You didn't mention testing (although I know you're a firm
believer in it).

With regards to the core dump, there are some systems you can't
get it on. But an assertion failure will still occur closer to
the point of failure, and the error message will generally give
you some indication as to what when wrong.

--
James Kanze

Ian Collins

unread,
Mar 15, 2010, 6:44:09 PM3/15/10
to

I do. By "a nebulous concept" I mean there isn't a standard definition
for release mode. Windows developers often use the term to
differentiate between VC++'s Debug and Release modes. Unix and embedded
developers tend not to use it at all!

--
Ian Collins

It is loading more messages.
0 new messages