473,320 Members | 1,691 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.

Assert vs. exceptions

When should one prefer assert-ing to throwing an exception?

Jul 23 '05 #1
11 2671
BigMan wrote:

When should one prefer assert-ing to throwing an exception?


assert-ing is a debug-build only tool. They are not present in
release-builds, that is the program as usually shiped to the
customer.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 23 '05 #2
On 13 Apr 2005 01:10:42 -0700, BigMan <Bi****@abv.bg> wrote:
When should one prefer assert-ing to throwing an exception?


assertions should protect from (not always obvious) mistakes of the
developer, e.g. using a pointer despite its being NULL.

exceptions are a way to handle errors that may legitimately occur at
runtime, e.g. the failure of trying to connect to some server (which may
not respond for various reasons).

Jul 23 '05 #3
BigMan wrote:
When should one prefer assert-ing to throwing an exception?


Always assert, unless you have no other choice, but even then consider
the exception to be a design flaw to be eliminated.

Jul 23 '05 #4
BigMan wrote:
When should one prefer assert-ing to throwing an exception?


The latter spanks the user. The former spanks the programmer.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 23 '05 #5
BigMan wrote:
When should one prefer assert-ing to throwing an exception?


The assert macro is used to help programmers detect bugs
and *not* exceptions.

An exception is an unpredictable but expected event
which cannot be prevented and must be handled.
Exceptions should be handled to the extent possible
at the point where they are first detected.
If the exception cannot be handled completely
in the function where it is first detected,
all of the information required to handle the exception
in the calling program should be encoded in an exception object
and that object should be passed back to the calling program
as a return value by "throwing an exception".

Programming errors (bugs) are *not* exceptions.
Bugs are unexpected events which, once detected,
are always predicable and preventable by fixing the bug.
You can't "handle" bugs except by fixing them.
Once you have found and fixed all of the bugs,
the assert macros are no longer necessary
and you should turn them off by defining the NDEBUG macro.

Allowing assertions to persist in distributed software
only means that you haven't finished testing and debugging.
This is sometimes acceptable in alpha and beta distributions
but very unprofessional otherwise.
Jul 23 '05 #6
My experience shows that if the caller of a library function must take
further actions based on the return value (e.g. in a switch statement),
they should watch out for unexpected return values (usually one puts a
default clause to catch such cases). So, should I assert( false); in
the default clause or should I throw an exception there?
And what about the case where the same developer implements the caller
and the callee in the same source file?

Jul 23 '05 #7
BigMan wrote:
My experience shows that if the caller of a library function must take
further actions based on the return value (e.g. in a switch statement),
they should watch out for unexpected return values (usually one puts a
default clause to catch such cases). So, should I assert( false); in
the default clause or should I throw an exception there?
Whose fault is the error? You describe a programmer not implementing all
possibilities in a switch. That's an assertion.

However, if a long list of return values might be the user's fault, throw an
exception. For example, if you disconnect your 'net connection, the sockets
library could return any number of time-outs, dropped signals, etc.
Translate them into a string and stick them into the user's face.

Also, write all your code exception-safe and exception-neutral. You should
generally roll state back to the point of the last program input.
And what about the case where the same developer implements the caller
and the callee in the same source file?


Not relevant - the biggest distinction is whether the fault is the user's or
the programmer's. For example, users should not disconnect their 'net
connections while browsing. (Your ISP is also a user;)

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 23 '05 #8


BigMan wrote:
My experience shows that if the caller of a library function must take
further actions based on the return value (e.g. in a switch statement),
they should watch out for unexpected return values (usually one puts a
default clause to catch such cases). So, should I assert( false); in
the default clause or should I throw an exception there?
And what about the case where the same developer implements the caller
and the callee in the same source file?


Here we have a simple rule on who gets to fix a bug.

"The person with responsibilty for the code that supplied the
input that asserted gets to fix the code."

after 15 years of this policy it is typical to find in our methods more
asserions than live code.

In your example of a switch most of our default statements will
ASSERT_MISSING_CASE.

Jul 23 '05 #9
lilburne wrote:
Here we have a simple rule on who gets to fix a bug.

"The person with responsibilty for the code that supplied the
input that asserted gets to fix the code."

after 15 years of this policy it is typical to find in our methods more
asserions than live code.


That is such a good rule that I should not go extreme on you.

However, some people claim a team should pair program, rotate pairs
frequently, own tasks not code, and work on any code in the system to finish
a task. Shared code ownership leads to elegant code that looks like it was
written by a single, very intellegent, individual. However, the team might
honestly not know who wrote what code.

They also claim this policy leads to a very low defect rate, and a very high
test/code ratio.

--
Phlip
http://industrialxp.org/community/bi...UserInterfaces
Jul 23 '05 #10
Phlip wrote:
lilburne wrote:

Here we have a simple rule on who gets to fix a bug.

"The person with responsibilty for the code that supplied the
input that asserted gets to fix the code."

after 15 years of this policy it is typical to find in our methods more
asserions than live code.

That is such a good rule that I should not go extreme on you.

However, some people claim a team should pair program, rotate pairs
frequently, own tasks not code, and work on any code in the system to finish
a task. Shared code ownership leads to elegant code that looks like it was
written by a single, very intellegent, individual. However, the team might
honestly not know who wrote what code.

We don't normally pair program and although we don't really have code
ownership it is sometimes difficult to avoid. You really don't want
anyone messing with the innards of a continuous 5 axis machining
algorithm. Each change to a function is documented, with references back
to the originating requirement, or bug report, log of test results,
design discussions, proposed change discussions. Additionally any
modification or creation of a document, bug report, or enhancement
request, gets automatically mailed to every team member, or indeed
anyone in the company that expresses an interest.

Jul 23 '05 #11
BigMan wrote:
My experience shows that,
if the caller of a library function must take further actions
based on the return value (e.g. in a switch statement),
they should watch out for unexpected return values
(usually one puts a default clause to catch such cases).
So, should I assert(false); in the default clause?
No!
The default clause should be used to handle exceptions.
Or should I throw an exception there?
You must try to handle the exception in the default clause.
If you can't handle the exception completely
in the context of the function then you should
create an exception object that contains all of the information
required to handle the exception in the calling program
and return or throw that exception.
And what about the case
where the same developer implements the caller and the callee
in the same source file?
What about it?

cat main.cc #include <iostream>
#include <cstdlib>
#include <cassert>

int f(void) {
return rand()%9 + 1;
}

int main(int argc, char* argv[]) {
srand((1 < argc)? atoi(argv[1]): 0);
int i = f();
assert(0 < i);
switch(i) {
case 1:
std::cout << "first" << std::endl;
break;
case 2:
std::cout << "second" << std::endl;
break;
case 3:
std::cout << "third" << std::endl;
break;
default:
std::cout << "Sorry! You lose." << std::endl;
}
return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

second
Jul 23 '05 #12

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...
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...
12
by: Christian Christmann | last post by:
Hi, assert and error handling can be used for similar purposes. When should one use assert instead of try/catch and in which cases the error handling is preferable? I've read somewhere that...
2
by: scsharma | last post by:
Hi, I am having trouble with following piece of code: Trace.Assert(args.Length >=1,"Invalid Argument list. Statement Date is mandatory input"); I expect the code to stop execution and exit...
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...
29
by: mailforpr | last post by:
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...
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...
0
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...
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: 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)...
1
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: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.