473,732 Members | 2,214 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
29 2509
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.d udewrote in message
news:YU******** *******@newssvr 14.news.prodigy .com...
Duane Hebert wrote:
>"Julián Albo" <JU********@ter ra.eswrote in message
news:45******* *@x-privat.org...
>>Duane Hebert wrote:

And with exception you only need:

perform_transac tion ();

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_transac tion();

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********@ter ra.eswrote in message
news:45******** @x-privat.org...
Duane Hebert wrote:
>>And with exception you only need:

perform_transac tion ();

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_transac tion()?
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.d udewrote in message
news:YU******** *******@newssvr 14.news.prodigy .com...
Duane Hebert wrote:
"Julián Albo" <JU********@ter ra.eswrote in message
news:45******** @x-privat.org...
Duane Hebert wrote:

And with exception you only need:

perform_transac tion ();

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_transac tion();

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_transac tion.
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_transac tion.
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_transac tion.
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_transac tion 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_transac tion.
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_transac tion 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*******@googl email.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
3591
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 very early draft for a new "assert" syntax: This was inspired in Ruby's assert syntax. I'm not familiar with Ruby at all, so the chances are that this piece of code is broken, but I think the idea is very obvious. In Ruby, assert is simply a...
1
1867
by: Antti Granqvist | last post by:
Hello! I have following object relations: Competition 1--* Category 1--* Course 1 | | * Course
11
2712
by: BigMan | last post by:
When should one prefer assert-ing to throwing an exception?
10
4998
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 test all the corner cases, and thus assert() does not work as good as before. The problem is if there are something really bad which was not captured by assert(), then in runtime, most likely the program will crash. This is the worst user...
47
3093
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 can see that it would be poor style to use it for commonly encountered errors, but what about truly exceptional errors that would rarely if ever be encountered?
1
2386
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 look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
15
1379
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 "16" (at least on python 2.4.4 (Linux) and 2.5 (Wine).
8
6140
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 system (or software) boundaries I throw a logic error (interface specification not met, etc). This implies the system is logically erroneous. I
10
3387
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 am assuming this is the same with ..NET too? Debug.Assert isn't compiled into a Release build? The other thing I am curious about is this public void DoSomething(Person p) { if (p == null)
0
8946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8774
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9181
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.