473,583 Members | 3,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

assert to exception : what is the scenario

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 experience.

Exception at least is better in that it has "graceful" exit.

I did not use exception before as I was told gcc3.2.2 did not support
exception very well, now my company is using gcc 3.2.3 which I am told
is better to handle exception. (Is this true?)

My current plan is to do some sort of editor string replacement so
that assert() is to be exception.

One thing is, I use lofs of assert(), some of them are in pretty deep
function call chain stack, then that means I need to add "throw
exception" declaration to almost all the functions.

While I will only have one catch statement on the very top, so in
order for the top function to receive the exception, I need to have
"throw exception" all the way from the deepest function in the stack.

How do you think my plan, how about gcc3.2.3 exception support?

Any suggestion is highly appreciated.

Jul 23 '05 #1
10 4977

<li*****@hotmai l.com> skrev i en meddelelse
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
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 experience.

Exception at least is better in that it has "graceful" exit.

Assert is for debug, thus the user should not see that. But let us assume
that you do send your debug-code to beta-testers. In that case, the assert
is much better. It gives you a core dump that helps you find out what the
problem is.
I did not use exception before as I was told gcc3.2.2 did not support
exception very well, now my company is using gcc 3.2.3 which I am told
is better to handle exception. (Is this true?) Unfortunately, I cannot help you here.
My current plan is to do some sort of editor string replacement so
that assert() is to be exception. If you decide to hang on to your scheme, you should probably replace the
assert-macro with another macro. That macro could then test the condition
and do the job. Something like
#define assert_throw(_c ond) do { if (!_cond) throw
my_assert_signa l(#_cond); } while (false)
One thing is, I use lofs of assert(), some of them are in pretty deep
function call chain stack, then that means I need to add "throw
exception" declaration to almost all the functions. No. Only if those functions have a throw-specification already.

While I will only have one catch statement on the very top, so in
order for the top function to receive the exception, I need to have
"throw exception" all the way from the deepest function in the stack.

How do you think my plan, how about gcc3.2.3 exception support?
I believe assert is for debug-builds only - not something you would send to
a real user. Perhaps some of your asserts check your environment instead of
your logic?

Any suggestion is highly appreciated.


/Peter
Jul 23 '05 #2

linq...@hotmail .com wrote:
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 experience.

Exception at least is better in that it has "graceful" exit.


You should only use 'assert' in cases where the program *should* abort
if the assertion fails. In particular, use assert to enforce program
invariants (e.g,. a value that you stored into a container is in the
container when you 'find' it).

Use exceptions for *exceptional* errors for which there may or may not
be a recovery action (e.g., could not allocate memory from a pooled
allocator).

Use return codes for all other errors (e.g., could not connect to
server, result of translation from string to int failed, etc).

As for testing corner cases, an effective method is to break your
program into a hierarchy of (small) components with an explicitly
stated contract for each method, and test each component completely in
isolation from the bottom up. It helps a great deal to *state* the
contract for each method (what values are returned under various
circumstances, what is undefined behavior, what are the effects of
error conditions on arguments, etc) both for the purpose of writing the
implementation and for testing the method. If you can state the domain
and range of a function, it is fairly straightforward to test it.

/david

Jul 23 '05 #3

Peter Koch Larsen wrote:
<li*****@hotmai l.com> skrev i en meddelelse
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
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 experience.

Exception at least is better in that it has "graceful" exit.

Assert is for debug, thus the user should not see that. But let us

assume that you do send your debug-code to beta-testers. In that case, the assert is much better. It gives you a core dump that helps you find out what the problem is.
I did not use exception before as I was told gcc3.2.2 did not support exception very well, now my company is using gcc 3.2.3 which I am told is better to handle exception. (Is this true?) Unfortunately, I cannot help you here.

My current plan is to do some sort of editor string replacement so
that assert() is to be exception.

If you decide to hang on to your scheme, you should probably replace

the assert-macro with another macro. That macro could then test the condition and do the job. Something like
#define assert_throw(_c ond) do { if (!_cond) throw
my_assert_signa l(#_cond); } while (false)

One thing is, I use lofs of assert(), some of them are in pretty deep function call chain stack, then that means I need to add "throw
exception" declaration to almost all the functions. No. Only if those functions have a throw-specification already.

While I will only have one catch statement on the very top, so in
order for the top function to receive the exception, I need to have
"throw exception" all the way from the deepest function in the stack.
How do you think my plan, how about gcc3.2.3 exception support?


I believe assert is for debug-builds only - not something you would

send to a real user. Perhaps some of your asserts check your environment instead of your logic?

Any suggestion is highly appreciated.


/Peter


Thanks for the reply.

Like you said assert() is for debug, for my case the assert() call will
be removed in optimized compile, it only stays in the debug version.

One thing I want to make sure, let's say the function call is like
this:
func1()
--> func2()
--> func3()
In func3() I throw an exception, and func3() declares "throw
exception". Then in order for func1() to receive the exception, func2()
must declares "throw expetion". Is this right?

More details like this,

int func1(){
...
try {
func2();
}
catch excpetion {
...
}
}

int func2() throw exception {
^^^^^^^^^^^^^^^ ^ -- I must have this declaration,
right?
func3();
}

int func3() throw exception {
...
throw exception;
}

Jul 23 '05 #4

<li*****@hotmai l.com> wrote in message

Like you said assert() is for debug, for my case the assert() call will
be removed in optimized compile, it only stays in the debug version.

One thing I want to make sure, let's say the function call is like
this:
func1()
--> func2()
--> func3()
In func3() I throw an exception, and func3() declares "throw
exception". Then in order for func1() to receive the exception, func2()
must declares "throw expetion". Is this right?

More details like this,

int func1(){
...
try {
func2();
}
catch excpetion {
...
}
}

int func2() throw exception {
^^^^^^^^^^^^^^^ ^ -- I must have this declaration,
right?
func3();
}

int func3() throw exception {
...
throw exception;
}


Now you're talking about exception specifications. There is no requirement
that you provide exception specifications. Any function can throw an
exception, and any calling function can catch exceptions (either using the
catch-all "..." or the specific exception type). You do not have to declare
(nor have I ever used) exception specifications (unless of course that is
something your employer requires). Exception specifications do not actually
allow or prevent exceptions from being passed (or caught), but are rather
intended as a tool for programmers to use to know what exceptions *might* be
expected to be thrown out of a given function. But in practice, that may be
incredibly difficult to know for sure, and in the opinion of many (myself
included) they're just a waste of time.

-Howard

Jul 23 '05 #5
> While I will only have one catch statement on the very top, so in
order for the top function to receive the exception, I need to have
"throw exception" all the way from the deepest function in the stack.


Reading your description I do not think you will really benefit from
exceptions. The strength of exceptions is that they may be caught and
handled everywhere. If you only provide a top level catch clause (presumably
with some user interface telling that program is shutting down), you might
as well replace all asserts with a call to the function that does exactly
the same.

I do not see why you think that exceptions shut program more gracefully than
asserts. I believe it makes no difference whatsoever - the program just
crashes in both cases.

Moreover, it is often much easier to debug an assert-crashing program than
exception-crashing. The reason is the stack frame is still there in case of
assert, while in top-level exception handler it is already completely
unwound and useless. In other words you don't know where the exception is
coming from, unless you include that information in the exception itself.

cheers,
M.
Jul 23 '05 #6

Marcin Kalicinski wrote:
While I will only have one catch statement on the very top, so in
order for the top function to receive the exception, I need to have
"throw exception" all the way from the deepest function in the
stack.
Reading your description I do not think you will really benefit from
exceptions. The strength of exceptions is that they may be caught and handled everywhere. If you only provide a top level catch clause (presumably with some user interface telling that program is shutting down), you might as well replace all asserts with a call to the function that does exactly the same.

I do not see why you think that exceptions shut program more gracefully than asserts. I believe it makes no difference whatsoever - the program just crashes in both cases.

Moreover, it is often much easier to debug an assert-crashing program than exception-crashing. The reason is the stack frame is still there in case of assert, while in top-level exception handler it is already completely unwound and useless. In other words you don't know where the exception is coming from, unless you include that information in the exception itself.
cheers,
M.

While I do not quite agree with you. assert() is a macro, when you
build the code without DEBUG in the compiler option, it disappears from
the code. And if an error slips by, then it means crash.

Exception is better here because you can tell user some fatal error
happens, but user has the choise either close the application or call
some other utility. This does not cause the whole software crash.

I prefer exception over calling a function in that you still need come
out that function at some point, so you are still in trouble.

Thanks.

Jul 23 '05 #7
>>Moreover, it is often much easier to debug an assert-crashing program

than
exception-crashing. The reason is the stack frame is still there in
case of
assert, while in top-level exception handler it is already completely


unwound and useless. In other words you don't know where the


exception is
coming from, unless you include that information in the exception


itself.
cheers,
M.


While I do not quite agree with you. assert() is a macro, when you
build the code without DEBUG in the compiler option, it disappears from
the code. And if an error slips by, then it means crash.


The fact that it is a macro and it disapears from your code is a
feature. Assert is for testing correctness of your code. Assert
disapears when you are not debugging because this allows you to call
some heavy checking function inside it. For example:

* You could have a linked list (or some structure more complex). You may
want to test in many places if "n->next->prev == n" or not. You may want
to do this after each removal, or addition of elements. And you may want
to do for every element on the list for each addition or removal.

Also, you may enforce some policy: "Whenever you call a certain member
function, the object must necessarly be in a certain state. If it is
not, then it is a bug."

Exception is better here because you can tell user some fatal error
happens, but user has the choise either close the application or call
some other utility. This does not cause the whole software crash.
Assertions are there to prove that your code is right. What you want to
do needs no execption. Just a function for "cleaning up the mess".

I prefer exception over calling a function in that you still need come
out that function at some point, so you are still in trouble.


Assertion is not what you want because it is for development. But don't
assume that exception *is* what you want. Maybe you should do something
like:
assert( fact );
if ( ! fact ) clean_up_the_me ss( __FILE__, __LINE__ );

But some "execptions " are not necessarly bugs (they could be a bad
input). And some bugs are very unlikely to happen if you passed the
development fase without them beeing "catched" by your "assertions ". So,
some times you only need an "assert", some times you only need your
"clean_up_the_m ess", and some times you need both.

By the way, what Marcin was saying was that it is much better to have a
clean_up_the_me ss function then simply "if ( !fact ) throw MyException;"
because the exception messes up with the call stack.

Another thing. If you use assert for something that is not a real bug,
for example, a wrong input that would overflow some buffer, then you are
in trouble because the non-debug version will contain a buffer overflow
bug. Assert is for debugging only. Your program behaviour, supposing it
is free of bugs, should not change if they are ommited or not.

Andre Caldas.
Jul 23 '05 #8
Check out "Debugging Production Software" in the June, 2005 edition of
Dr. Dobb's.

</dib>

Jul 23 '05 #9

Andre Caldas wrote:
Moreover, it is often much easier to debug an assert-crashing
program
than
exception-crashing. The reason is the stack frame is still there in
case of
assert, while in top-level exception handler it is already
completely
unwound and useless. In other words you don't know where the


exception is
coming from, unless you include that information in the exception


itself.
cheers,
M.


While I do not quite agree with you. assert() is a macro, when you
build the code without DEBUG in the compiler option, it disappears from the code. And if an error slips by, then it means crash.


The fact that it is a macro and it disapears from your code is a
feature. Assert is for testing correctness of your code. Assert
disapears when you are not debugging because this allows you to call
some heavy checking function inside it. For example:

* You could have a linked list (or some structure more complex). You

may want to test in many places if "n->next->prev == n" or not. You may want to do this after each removal, or addition of elements. And you may want to do for every element on the list for each addition or removal.

Also, you may enforce some policy: "Whenever you call a certain member function, the object must necessarly be in a certain state. If it is
not, then it is a bug."

Exception is better here because you can tell user some fatal error
happens, but user has the choise either close the application or call some other utility. This does not cause the whole software crash.
Assertions are there to prove that your code is right. What you want

to do needs no execption. Just a function for "cleaning up the mess".

I prefer exception over calling a function in that you still need come out that function at some point, so you are still in trouble.
Assertion is not what you want because it is for development. But

don't assume that exception *is* what you want. Maybe you should do something like:
assert( fact );
if ( ! fact ) clean_up_the_me ss( __FILE__, __LINE__ );

Let's say the function statck is like this,
main()
---> fun1()
---> fun2()
and in fun2() you have this clean_up_the_me ss() called. The problem is
for the bug that assert() did not catch in debug version, that usually
is a critical one, that means after you clean up the messed
environment, the only option for you is to exit, not continue. But the
problem is you need to exit all the way from fun2(), to fun1(), and to
main() finally.

You need to have the code in each function to check the return the
value of the sub-function, fun1() checks fun2(), main() checks fun1(),
etc. Well this should be a good practice, in reality world, we do not.

That is the thing I love exception, it unwinds the function call stack
all the way up, until some point you believe it is necessary to do
clean up.

Maybe I do not get your idea in full, enjoying this thread.

Jul 23 '05 #10

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

Similar topics

28
3566
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...
3
3956
by: Thomas Guettler | last post by:
Hi, Python 2.3.3 (#1, Feb 5 2005, 16:22:10) on linux2 >>> assert 0, "foo" Traceback (most recent call last): File "<stdin>", line 1, in ? AssertionError: foo >>> assert(0, "foo") >>>
11
2697
by: BigMan | last post by:
When should one prefer assert-ing to throwing an exception?
21
7238
by: Giuseppe | last post by:
is assert() for debug only or not? Is it possible that I have seen the use of assert() in the Borland c++ 32 compiler (so assert is not for debug only)?
2
5858
by: cody | last post by:
System.Diagnostics.Debug.Assert(); Hello??? A language should encourage programmers to heavily use the assert-feature, since it improves safety, stability, readability and maintainability of software. Most language designers recognized this, see C/C++ and Java which supports an assert keyword. My question now is, will C# support in future...
28
5712
by: lovecreatesbeauty | last post by:
Besides printing out for example " a.out: p113.c:8: main: Assertion `0' failed. Aborted " and a switch option NDEBUG, what other benefits does assert() provide in any scope of designing, debugging/coding and/or testing? Do you prefer the if statement of the language to the assert MACRO of the precompiler?
29
2490
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 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...
8
6103
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
32
2052
by: bingfeng | last post by:
hello, please see following two code snatches: 1. int foo (const char* some) { assert(some); if (!some) { return -1; //-1 indicates error }
0
7893
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...
0
7821
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...
0
8172
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. ...
1
7928
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8188
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...
1
5695
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3813
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3839
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1422
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.