473,320 Members | 2,029 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Understanding Assert and Exceptions

Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception. Except for catching the exception
and printing "Uh, oh" to the screen. I also think that in most cases
there's simply no way to handle an exception properly, because what can
one do about an integer overflow? Reassign values? Restart the program?
The problem will still be existing. I think that an integer overflow is
not an exception, but sluttish programming.

Now I think printing a message "There's a bug - I'm so sorry" is much
better than some bizarre error message provided by the operating
system. Kind of better than assert, which disappears when I compile the
release version and causes the bizarre error message if the bug's still
there.

My conclusion: throwing an exception is still better than assert, for
you can always print a user friendly message to the screen. You could
even provide a dialog or something and ask the user to write down the
steps that caused the bug in a text field.

I saw some guy named "lilburne" say "Use always assert, unless you have
no other choice, but even then consider the exception to be a design
flaw to be eliminated."

Somehow, I agree. After all, if you check for an error condition, then
in some sense you expect it to happen and it is no exception
whatsoever.

Now, if you happen to have any exceptional situations and you deside to
throw an exception, this is more an excuse for poor programming, I
think. Again, what can one do about an integer overflow? Or a wrong
static_cast?

Knowing that something went wrong seems to be the only good point about
exceptions to me anyway. But then again, I am all for assert, as they
don't throw an excuse to the end user. But this has to be done, anyhow.
What do you think?

Oct 14 '06 #1
29 2460
Correction: ... as they don't throw an excuse AT the end user.

Oct 14 '06 #2
posted:
Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception.

There's isn't really a rule of thumb -- it's intuition more than anything.

My conclusion: throwing an exception is still better than assert, for
you can always print a user friendly message to the screen. You could
even provide a dialog or something and ask the user to write down the
steps that caused the bug in a text field.

Unless, of course, you hijack "assert" and make it more user-friendly.

I saw some guy named "lilburne" say "Use always assert, unless you have
no other choice, but even then consider the exception to be a design
flaw to be eliminated."

Somehow, I agree. After all, if you check for an error condition, then
in some sense you expect it to happen and it is no exception
whatsoever.

People who make blanket rules of thumb like that tend to be improficient.

What do you think?

I use "assert" to indicate that something WRONG... W-R-O-N-G has happened,
such as a letter being '7'.

I throw an exceptio when something exceptional has happened, such as when a
random number is exactly 256.

--

Frederick Gotham
Oct 14 '06 #3

Frederick Gotham wrote:

I use "assert" to indicate that something WRONG... W-R-O-N-G has happened,
such as a letter being '7'.

I throw an exceptio when something exceptional has happened, such as when a
random number is exactly 256.
Why would that warrant an exception?

Fred, show us some real code where you would throw an exception in that
instance.

I use exceptions quite a bit (e.g., in a compiler when the source code
has a syntax error), but I don't know anyone who would use an exception
the way you suggest, except in jest.

Best regards,

Tom

Oct 14 '06 #4
ma*******@googlemail.com wrote:
Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception. Except for catching the exception
and printing "Uh, oh" to the screen. I also think that in most cases
there's simply no way to handle an exception properly, because what can
one do about an integer overflow? Reassign values? Restart the program?
The problem will still be existing. I think that an integer overflow is
not an exception, but sluttish programming.

Now I think printing a message "There's a bug - I'm so sorry" is much
better than some bizarre error message provided by the operating
system. Kind of better than assert, which disappears when I compile the
release version and causes the bizarre error message if the bug's still
there.

My conclusion: throwing an exception is still better than assert, for
you can always print a user friendly message to the screen. You could
even provide a dialog or something and ask the user to write down the
steps that caused the bug in a text field.

I saw some guy named "lilburne" say "Use always assert, unless you have
no other choice, but even then consider the exception to be a design
flaw to be eliminated."

Somehow, I agree. After all, if you check for an error condition, then
in some sense you expect it to happen and it is no exception
whatsoever.

Now, if you happen to have any exceptional situations and you deside to
throw an exception, this is more an excuse for poor programming, I
think. Again, what can one do about an integer overflow? Or a wrong
static_cast?
Those are not examples where exceptions should be used. You use exceptions
to indicate failures that are not bugs. E.g.:

class TCP_Connection {

TCP_Connection ( some args )
: some initializations
{
try to establish the connection.
if you fail, throw an exception indicating the failure.
}

...
};

It is pretty clear that an assert would be wrong: even if your code is 100%
correct, the computers network might just be down. Also, the program can do
something in this case: catch the exception and tell the user to bring up
the network and to try again then.

The point of throwing the exception is to separate concerns: the
TCP_Conncection class could provide handling in place. However, that is
less flexible. It can become unacceptably rigid, if TCP_Connection is part
of a library. Then you want the client to be able to decide how errors
should be handled. Thus, you just throw an exception and let the client
provide the handler. That is what exceptions are designed for: postponing
the handling of resource failures.

Knowing that something went wrong seems to be the only good point about
exceptions to me anyway. But then again, I am all for assert, as they
don't throw an excuse to the end user. But this has to be done, anyhow.
Huh?
Best

Kai-Uwe Bux
Oct 14 '06 #5
ma*******@googlemail.com wrote:
I saw some guy named "lilburne" say "Use always assert, unless you have
no other choice, but even then consider the exception to be a design
flaw to be eliminated."
Somehow, I agree. After all, if you check for an error condition, then
in some sense you expect it to happen and it is no exception
whatsoever.
Maybe we need a new concept, in addition to exceptions we can introduce
the "impossibilities". Instead of failing an assertion, we throw an
impossibility, like throwing an exception but without any way to catch it
X-)

More seriously: an exception is not (for me and meny others) something I'm
sure will never happen. It's something that, for infrequent of for the way
yo handle it, is better to keep separate from the normal flow.

For example, reaching eof when reading a text file is hardly considered
exceptional, but reaching it in the middle of a field of fixed length in a
binary file is a good candidate for exception.

Maybe this can also be considered a design flaw, we must design systems when
files never are corrupted, disks never fails, users don't make mistakes...
Maybe eliminate users can be a first step in that direction?

--
Salu2
Oct 14 '06 #6
<ma*******@googlemail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception. Except for catching the exception
and printing "Uh, oh" to the screen. I also think that in most cases
there's simply no way to handle an exception properly, because what can
one do about an integer overflow? Reassign values? Restart the program?
The problem will still be existing. I think that an integer overflow is
not an exception, but sluttish programming.

Now I think printing a message "There's a bug - I'm so sorry" is much
better than some bizarre error message provided by the operating
system. Kind of better than assert, which disappears when I compile the
release version and causes the bizarre error message if the bug's still
there.

My conclusion: throwing an exception is still better than assert, for
you can always print a user friendly message to the screen. You could
even provide a dialog or something and ask the user to write down the
steps that caused the bug in a text field.

I saw some guy named "lilburne" say "Use always assert, unless you have
no other choice, but even then consider the exception to be a design
flaw to be eliminated."

Somehow, I agree. After all, if you check for an error condition, then
in some sense you expect it to happen and it is no exception
whatsoever.

Now, if you happen to have any exceptional situations and you deside to
throw an exception, this is more an excuse for poor programming, I
think. Again, what can one do about an integer overflow? Or a wrong
static_cast?

Knowing that something went wrong seems to be the only good point about
exceptions to me anyway. But then again, I am all for assert, as they
don't throw an excuse to the end user. But this has to be done, anyhow.
What do you think?
I normally very seldom throw, but I tend to use assert a bit. But there are
good reasons for using throw and catch.

One reason I am doing it is because I have a function that returns a
referernce to a map, although the key may not exist in the map. I got into
a quandry as to what do I return, how do I tell the calling method that the
key was not found, and the best solution I came up with was to throw if it
was not found, and I found out it worked rather well.

CPlayer& FindPlayer( const SOCKET Socket )
{
// Get a reference in the map for this player
map_player::iterator it = World.ConnectedPlayers.find( Socket );
if ( it != World.ConnectedPlayers.end() )
return (*it).second;
else
throw 0;
}

// First lets see if this player is already connected.
try
{
FindPlayer( wsp.Name );
// We didn't throw, so the player name is already logged in
World.MessageBuffer.push_back( LogMessage( "Player " +
jml::StrmConvert( wsp.Name ) + " Tried to log in twice. IP " + IP ) );
return ACCEPT_CLIENT | ( MSG_ALREADY_LOGGED_IN << 8 );
}
catch ( int )
{
}

// later

try
{
CPlayer& ThisPlayer = FindPlayer( Socket );
PlayerLeft( ThisPlayer );
}
catch ( int )
{
World.MessageBuffer.push_back( "Unlogged in socket " +
jml::StrmConvert( Socket ) + " disconnected." );
}

Basically, I will only throw if I can catch it and do something about it,
and there is no better way to handle handle it (return a value from the
function, etc...)

Assert I use only when I want to make sure code isn't running, or that some
value is true when I'm designing. Here's one case (that is actually not
needed)

class CMap
{
private:

// No copy or assignment yet so disable by making private.
CMap ( CMap const& /*CopyThis*/ ) { assert ( false ); }; // Copy
constructor.
CMap& operator=( CMap const& /*CopyThis*/ ) { assert ( false ); }; //
Assignment.
// ...
}

I have made the copy and assignment constructors private beause this class
can not be copied (pointers, etc..) so I just threw the assert in there to
make sure somehow it was never being called (but since it's private, it
shouldn't anyway).

exceptions and assert are tools, and as such should be used when they are
appropriate. It is said that when all you have is a hammer, then everything
starts to look like a nail, but in this case we have many more tools in our
toolboxes.
Oct 15 '06 #7
On Sat, 14 Oct 2006 19:17:44 -0400, Kai-Uwe Bux wrote:
>The point of throwing the exception is to separate concerns: the
TCP_Conncection class could provide handling in place. However, that is
less flexible. It can become unacceptably rigid, if TCP_Connection is part
of a library. Then you want the client to be able to decide how errors
should be handled. Thus, you just throw an exception and let the client
provide the handler. That is what exceptions are designed for: postponing
the handling of resource failures.
>Knowing that something went wrong seems to be the only good point about
exceptions to me anyway. But then again, I am all for assert, as they
don't throw an excuse to the end user. But this has to be done, anyhow.

Huh?
assert is a debug aid, ie. the only purpose of assert is to find bugs
in your program. assert is a macro that is not present in the release
version of the program.
OTOH, exceptions indicate expected runtime failures and errors (but
not bugs). They need to be handled (caught) in the program somewhere.
In sum, asserts and exceptions serve different purposes and have
nothing to do with each other.

Best wishes,
Roland Pibinger
Oct 15 '06 #8
Let's say you are writing a banking program. You are using libraries to
do certain tasks so you don't have to reinvent the wheel. And in one of
the libraries there is one very nifty function:

void perform_transaction();

Now as a user of the library what do you expect when perform_transaction
encounters an exceptional condition such as a runtime error?

What happens if all perform_transaction does is to prints out "Uh, oh,
blah blah blah". Not a good idea because:

1. There is no screen
2. Even if there is a screen it doesn't know what language should be used
3. It fails to stop you, the caller, from doing the next step. If your
next step is to ask the user to pay for the transaction, you will get a
customer complain.

Hope that convinces you that perform_transaction() really shouldn't
handle the exception on its own. What it should do, is to stop the
current transaction and notify you, the caller, what just happened, so
you can handle the problem better because you know if there is a screen,
the language of the customer and how to drop the interaction etc.

Regards,
Ben
Oct 15 '06 #9
On 14 Oct 2006 16:12:44 -0700 in comp.lang.c++, "Thomas Tutone"
<Th***********@yahoo.comwrote,
>
Frederick Gotham wrote:

>I use "assert" to indicate that something WRONG... W-R-O-N-G has happened,
such as a letter being '7'.

I throw an exceptio when something exceptional has happened, such as when a
random number is exactly 256.

Why would that warrant an exception?
It's supposed to be between 0 and 1.

Oct 15 '06 #10

"benben" <benhonghatgmaildotcom@nospamwrote in message
news:45**********************@news.optusnet.com.au ...
Let's say you are writing a banking program. You are using libraries to do
certain tasks so you don't have to reinvent the wheel. And in one of the
libraries there is one very nifty function:

void perform_transaction();

Now as a user of the library what do you expect when perform_transaction
encounters an exceptional condition such as a runtime error?

What happens if all perform_transaction does is to prints out "Uh, oh,
blah blah blah". Not a good idea because:

1. There is no screen
2. Even if there is a screen it doesn't know what language should be used
3. It fails to stop you, the caller, from doing the next step. If your
next step is to ask the user to pay for the transaction, you will get a
customer complain.

Hope that convinces you that perform_transaction() really shouldn't handle
the exception on its own. What it should do, is to stop the current
transaction and notify you, the caller, what just happened, so you can
handle the problem better because you know if there is a screen, the
language of the customer and how to drop the interaction etc.
So what's wrong with it becoming:
bool perform_transaction() and return false on
failure? Personally, I think throwing on a function
failure is bogus. I would reserve exceptions for exceptional
behavior and not for something that can be handled
easily by returning an error.
Oct 15 '06 #11
Duane Hebert wrote:
So what's wrong with it becoming:
bool perform_transaction() and return false on
failure?
Nothing "wrong". You can use any or other way depending on the intended use
of the function.

For example, if the function that calls perform_transaction does not want to
handle the error itself, but let it fall to the callee, it must do
something like:

if (! perform_transaction () )
{
// Maybe some cleaning here.
return false;
}

And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of execution.

--
Salu2
Oct 15 '06 #12
mailforpr wrote:
Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception.
Write lots of unit tests that crunch your code in various ways.

The situations your tests can't get to, such as a NULL pointer where it
shouldn't be, deserve assert() statements.

The situations they _can_ get to, your users _might_ get to. So that code
should throw assertions, and the test cases should catch them and pass.

Put another way, asserts and exceptions without unit tests are just a
two-legged stool. Not very useful, and no point distinguishing which leg is
which!

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Oct 15 '06 #13
benben wrote:
What happens if all perform_transaction does is to prints out "Uh, oh,
blah blah blah". Not a good idea because:

1. There is no screen
2. Even if there is a screen it doesn't know what language should be used
3. It fails to stop you, the caller, from doing the next step.
Kai-Uwe Bux wrote:
Then you want the client to be able to decide how errors
should be handled. Thus, you just throw an exception and let the client
provide the handler. That is what exceptions are designed for: postponing
the handling of resource failures.

I see.

Oct 15 '06 #14

"Julián Albo" <JU********@terra.eswrote in message
news:45********@x-privat.org...
Duane Hebert wrote:
>So what's wrong with it becoming:
bool perform_transaction() and return false on
failure?

Nothing "wrong". You can use any or other way depending on the intended
use
of the function.

For example, if the function that calls perform_transaction does not want
to
handle the error itself, but let it fall to the callee, it must do
something like:

if (! perform_transaction () )
{
// Maybe some cleaning here.
return false;
}

And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.
I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.
Oct 15 '06 #15
Duane Hebert wrote:
"Julián Albo" <JU********@terra.eswrote in message
news:45********@x-privat.org...
>Duane Hebert wrote:

And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.

I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.

If an exception is uncaught, eventually terminate() is called, causing
your program to drop dead.
Oct 16 '06 #16
Duane Hebert wrote:
>And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.

I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.
The point is that at some point I, or some other programmer that use the
function, can catch the exception. Or just let the program terminate, if
it's a simple command line tool used for people that knows how is written.

--
Salu2
Oct 16 '06 #17
Phlip wrote:
mailforpr wrote:
Sometimes, I can't think of any good reason why I should have the
program's logic thrown an exception.

Write lots of unit tests that crunch your code in various ways.

The situations your tests can't get to, such as a NULL pointer where it
shouldn't be, deserve assert() statements.

The situations they _can_ get to, your users _might_ get to. So that code
should throw assertions, and the test cases should catch them and pass.

Put another way, asserts and exceptions without unit tests are just a
two-legged stool. Not very useful, and no point distinguishing which leg is
which!
In many cases, you're right, but in a good many other cases, there is
no practical way to write comprehensive unit tests in any reasonable
amount of time. On a complex embedded system, for instance, one must
accurately simulate the hardware and timing of the system to catch bugs
with unit tests, but doing so is often not feasible. Testing must be
done, of course, but by necessity, it must be to a lesser degree of
thoroughness than some other application domains enjoy.

Cheers! --M

Oct 16 '06 #18
mlimber wrote:
In many cases, you're right, but in a good many other cases, there is
no practical way to write comprehensive unit tests in any reasonable
amount of time.
If you write them as you write the tested code, you can typically save most
of the time you'd spend debugging.

I use them in this case as an example of exercising the code, to distinguish
accessible but unpreventable problems from programmer errors. There are
other ways.
On a complex embedded system, for instance, one must
accurately simulate the hardware and timing of the system to catch bugs
with unit tests, but doing so is often not feasible. Testing must be
done, of course, but by necessity, it must be to a lesser degree of
thoroughness than some other application domains enjoy.
I thought embedded systems shunned exceptions, and I thought they also
leveraged alternative design techniques.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Oct 16 '06 #19
Phlip wrote:
mlimber wrote:
In many cases, you're right, but in a good many other cases, there is
no practical way to write comprehensive unit tests in any reasonable
amount of time.

If you write them as you write the tested code, you can typically save most
of the time you'd spend debugging.

I use them in this case as an example of exercising the code, to distinguish
accessible but unpreventable problems from programmer errors. There are
other ways.
Sure. But my point was that there are a good number of circumstances
where unit tests are simply not feasible (embedded systems is one,
legacy code with no existing unit tests is another) but where
exceptions and assertions can and should still be used.
On a complex embedded system, for instance, one must
accurately simulate the hardware and timing of the system to catch bugs
with unit tests, but doing so is often not feasible. Testing must be
done, of course, but by necessity, it must be to a lesser degree of
thoroughness than some other application domains enjoy.

I thought embedded systems shunned exceptions, and I thought they also
leveraged alternative design techniques.
Depends on the application of course, but Texas Instrument's (quite
conformant) C++ compiler supports exceptions for their DSPs.

Cheers! --M

Oct 16 '06 #20
mlimber wrote:
Sure. But my point was that there are a good number of circumstances
where unit tests are simply not feasible (embedded systems is one,
legacy code with no existing unit tests is another) but where
exceptions and assertions can and should still be used.
I suspect a mis-alignment here.

I meant that tests, exceptions, and assertions are a three-legged stool. I
think you mean that tests can absolve the need for some of them. Maybe. You
are correct that's the fuzzier topic!

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Oct 16 '06 #21

"red floyd" <no*****@here.dudewrote in message
news:YU***************@newssvr14.news.prodigy.com. ..
Duane Hebert wrote:
>"Julián Albo" <JU********@terra.eswrote in message
news:45********@x-privat.org...
>>Duane Hebert wrote:

And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.

I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.

If an exception is uncaught, eventually terminate() is called, causing
your program to drop dead.
Well that's my point. Saying that with an exception
you only need:

perform_transaction();

is only true if it's OK for your program to
terminate. Seems hard to grasp how failure
to perform a transaction should do that.

Normally you're going to have
to write a try/catch block around it. In that
case, it's no "cleaner" than the if block IMO.
Oct 16 '06 #22

"Julián Albo" <JU********@terra.eswrote in message
news:45********@x-privat.org...
Duane Hebert wrote:
>>And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.

I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.

The point is that at some point I, or some other programmer that use the
function, can catch the exception. Or just let the program terminate, if
it's a simple command line tool used for people that knows how is written.
And so then the exception example is not
so elegant. I would still have it return
a bool. If you want to bail at that point,
you can always let the caller throw if there's
no other way out. But how can you know that
from inside of perform_transaction()?
I don't think embracing exceptions
for error indication is the correct thing to do.
Feel free to have your own opinion <g>
Oct 16 '06 #23
Duane Hebert wrote:
>The point is that at some point I, or some other programmer that use the
function, can catch the exception. Or just let the program terminate, if
it's a simple command line tool used for people that knows how is
written.
And so then the exception example is not so elegant.
Don't see the point.
I would still have it return a bool.
Just do it. This is not a "Always do it that way" thing.
I don't think embracing exceptions for error indication is the correct
thing to do.
I don't think so. I also don't think that return error codes is "the
correct" thing. There are no one only correct way.

--
Salu2
Oct 16 '06 #24

Duane Hebert wrote:
"red floyd" <no*****@here.dudewrote in message
news:YU***************@newssvr14.news.prodigy.com. ..
Duane Hebert wrote:
"Julián Albo" <JU********@terra.eswrote in message
news:45********@x-privat.org...
Duane Hebert wrote:

And with exception you only need:

perform_transaction ();

And the error handling does not get mixed with the normal flow of
execution.

I don't get that. If you don't catch the exception
what is going to happen? At some point you
have to catch it and deal with the error anyway.
If an exception is uncaught, eventually terminate() is called, causing
your program to drop dead.

Well that's my point. Saying that with an exception
you only need:

perform_transaction();

is only true if it's OK for your program to
terminate.
No. It's also true if the error handling code is at some level above
the code that calls perform_transaction.
Seems hard to grasp how failure
to perform a transaction should do that.

Normally you're going to have
to write a try/catch block around it.
Yes, at some level, but not necessarily the same level as the call to
perform_transaction.
In that
case, it's no "cleaner" than the if block IMO.
A try-catch block is only no cleaner than an if-else block if the error
handling happens at the same level as the call to perform_transaction.
If the error handling happens further up the call stack then, with an
exception, all the intermediate layers can ignore the failure and
remain unchanged. Whereas, if perform_transaction returns an error code
or flag, every intermediate layer must have a return code and maybe an
if-else block added just to propogate the error state up to the level
that needs to know about it, which is definitely less clean than the
exception solution.

Gavin Deane

Oct 16 '06 #25
Gavin Deane wrote:
Duane Hebert wrote:
In that
case, it's no "cleaner" than the if block IMO.

A try-catch block is only no cleaner than an if-else block if the error
handling happens at the same level as the call to perform_transaction.
If the error handling happens further up the call stack then, with an
exception, all the intermediate layers can ignore the failure and
remain unchanged. Whereas, if perform_transaction returns an error code
or flag, every intermediate layer must have a return code and maybe an
if-else block added just to propogate the error state up to the level
that needs to know about it, which is definitely less clean than the
exception solution.
In other words:

int f1();
int f2();
int f3();
int f4();
int f5();
int f6();

int g1()
{
int rc = f1();
if( 0 != rc )
{
return rc;
}

rc = f2();
if( 0 != rc )
{
return rc;
}

rc = f3();
if( 0 != rc )
{
return rc;
}
return 0;
}

int g2()
{
int rc = f4();
if( 0 != rc )
{
return rc;
}

rc = f5();
if( 0 != rc )
{
return rc;
}

rc = f6();
if( 0 != rc )
{
return rc;
}
return 0;
}

int h()
{
int rc = g1();
if( 0 != rc )
{
// Do some error handling
return rc;
}

rc = g2();
if( 0 != rc )
{
// Do some error handling
return rc;
}
return 0;
}

Vs.

void f1();
void f2();
void f3();
void f4();
void f5();
void f6();

void g1()
{
f1();
f2();
f3();
}

void g2()
{
f4();
f5();
f6();
}

void h()
{
try
{
g1();
g2();
}
catch( const std::exception& e ) // and/or custom exception classes
{
// Do some error handling
}
}

While both leave the error handling proper to a higher level [viz., in
h()], the second version represents the program flow much more clearly
thanks to exceptions.

Cheers! --M

Oct 17 '06 #26
Phlip wrote:
mlimber wrote:
Sure. But my point was that there are a good number of circumstances
where unit tests are simply not feasible (embedded systems is one,
legacy code with no existing unit tests is another) but where
exceptions and assertions can and should still be used.

I suspect a mis-alignment here.

I meant that tests, exceptions, and assertions are a three-legged stool. I
think you mean that tests can absolve the need for some of them. Maybe. You
are correct that's the fuzzier topic!
It sounded to me like you were saying that using assertions and
exceptions is pointless (like a two-legged stool) unless there are unit
tests to back them up and test them out thoroughly. I'm saying that
sometimes it is not practical to build such a unit test suite but that
even in those case, exceptions and assertions can still be of great
utility.

Cheers! --M

Oct 17 '06 #27
ma*******@googlemail.com wrote:
My conclusion: throwing an exception is still better than assert, for
you can always print a user friendly message to the screen.
[...]
Now, if you happen to have any exceptional situations and you deside to
throw an exception, this is more an excuse for poor programming, I
think. Again, what can one do about an integer overflow? Or a wrong
static_cast?
[...]
What do you think?
Sutter and Alexandrescu in _C++ Coding Standards_ address error
handling policy in more detail than we will likely do here (but, for my
taste, even more detail than theirs would be useful!). Some key
summaries are:

Item 68: Assert liberally to document internal assumptions and
invariants. Be assertive! use assert or an equivalent liberally to
document assumptions internal to a module (i.e., where the caller and
callee are maintained by the same person or team) that must always be
true and otherwise represent programming errors (e.g., violations of a
function's postconditions detected by the caller of the function).

Item 70: Distinguish between errors and non-errors. A breach of
contract is an error: A function is a unit of work. Thus, failures
should be viewed as errors or otherwise based on their impact on
functions. Within a function f, a failure is an error if and only if it
violates one of f's preconditions or prevents f from meeting any of its
callees' preconditions, achieving any of f's own postconditions, or
reestablishing any invariant that f shares responsibility for
maintaining. In particular here we exclude internal programming errors
(i.e., where the caller and callee are the responsibility of the same
person or team, such as inside a module), which are a separate category
normally dealt with using assertions (see Item 68).

Item 72: Prefer to use exceptions to report errors. When harmed, take
excpetion: Prefer using exceptions over error codes to report errors.
Use status codes (e.g., return codes, errno) for errors when exceptions
cannot be used (see Item 62), and for conditions that are not errors
[e.g., when a key is not found in a std::map --M]. Use other methods,
such as graceful or ungraceful termination, when recovery is impossible
or not required.

Cheers! --M

Oct 17 '06 #28
mlimber wrote:
It sounded to me like you were saying that using assertions and
exceptions is pointless (like a two-legged stool) unless there are unit
tests to back them up and test them out thoroughly. I'm saying that
sometimes it is not practical to build such a unit test suite but that
even in those case, exceptions and assertions can still be of great
utility.
Always try to automate any test you can think of. Such tests reduce the time
you'll spend debugging, so they free up development time for more valuable
activities.

--
Phlip
http://www.greencheese.us/ZeekLand <-- NOT a blog!!!
Oct 17 '06 #29
Phlip wrote:
mlimber wrote:
It sounded to me like you were saying that using assertions and
exceptions is pointless (like a two-legged stool) unless there are unit
tests to back them up and test them out thoroughly. I'm saying that
sometimes it is not practical to build such a unit test suite but that
even in those case, exceptions and assertions can still be of great
utility.

Always try to automate any test you can think of. Such tests reduce the time
you'll spend debugging, so they free up development time for more valuable
activities.
Of course, but sometimes that just isn't practical. That's my point.
(This is no longer a C++ discussion, by the way, but a software
engineering one.)

Cheers! --M

Oct 17 '06 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

28
by: Fábio Mendes | last post by:
I'm sorry if it's an replicate. Either my e-mail program is messing with things or the python-list sent my msg to /dev/null. I couldn't find anything related in previous PEP's, so here it goes a...
1
by: Antti Granqvist | last post by:
Hello! I have following object relations: Competition 1--* Category 1--* Course 1 | | * Course
11
by: BigMan | last post by:
When should one prefer assert-ing to throwing an exception?
10
by: linq936 | last post by:
Hi, I have many assert() call in my code, now I am considering to replace them with exception. The reason I want to do this change is that with the program going bigger and bigger, it is hard to...
47
by: Rob Thorpe | last post by:
In general, is it considered bad practice to use asserts in production code? What about writing a macro that does the same as assert but continues to work regardless of the state of NDEBUG? I...
1
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I...
15
by: Jim B. Wilson | last post by:
Am I nuts? Or only profoundly confused? I expected the this little script to print "0": class foo(int): def __init__(self, value): self = value & 0xF print foo(0x10) Instead, it prints...
8
by: werasm | last post by:
Hi all, Care to share your thoughts on this, or point me to some thoughts already shared. My thoughts are like this (from a systems point of view): When I have logic errors outside of my...
10
by: Peter Morris | last post by:
In Delphi I used to use Assert as a development aid. During debug it would ensure that certain conditions were met but in the Release build the Asserts were not compiled into the application. I...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shćllîpôpď 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.