By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
426,115 Members | 894 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 426,115 IT Pros & Developers. It's quick & easy.

Code Style - Handling Returns

P: n/a
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}

Dec 13 '05 #1
Share this Question
Share on Google+
41 Replies


P: n/a
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?


I tend to prefer case 1 with RAII classes to handle cleanup which makes
it both exception safe and much less prone to error from code
maintenance adding a new if/return block.

Dec 13 '05 #2

P: n/a
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.
Regardless of your personal preference, writing

if (flag == false)

is silly. 'flag' already has type 'bool', so just write

if (!flag)

Same goes for

if (flag == true)

.. Just write

if (flag)

and drop the "== true" clutter.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}


Neither is better than the other.

I prefer

if (!myFunc1() || !myFunc2())
return;
// continue code

V
Dec 13 '05 #3

P: n/a
[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).

Regards,

Marcelo Pinto

Dec 13 '05 #4

P: n/a
Victor,

I just wrote that for clarity for the group. Thanks.

Dec 13 '05 #5

P: n/a
After putting some thought in this, it sounds like Gianni made a good
point that validating for failure after each call would be the better
approach since memory can be safely deallocated, messages logged, etc.
It also reads better on screen rather than having a deep nests.

And yes, I'm a strong believe in the '!'. Like I said earlier, I was
just trying to clarify for readability on the group board.

Dec 13 '05 #6

P: n/a
Jordan wrote:
Victor,

I just wrote that for clarity for the group. Thanks.


Wrote what?
Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Dec 13 '05 #7

P: n/a
On Tue, 13 Dec 2005 11:48:09 -0800, Marcelo Pinto wrote:
[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).


What is "not" in this example?

- Jay
Dec 13 '05 #8

P: n/a
Jay Nabonne wrote:
On Tue, 13 Dec 2005 11:48:09 -0800, Marcelo Pinto wrote:

[snip]
is silly. 'flag' already has type 'bool', so just write

if (!flag)


I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).

What is "not" in this example?


Uh... It's a keyword, the alternative spelling for '!'. What else could
it be?
Dec 13 '05 #9

P: n/a
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}


Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}

Or some variant thereof.

Regards,
Peter Jansson
Dec 13 '05 #10

P: n/a
Peter Jansson wrote:
[...]
Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}

Or some variant thereof.


There is a school of thought out there that strongly discourages
using exception handling to handle something that is normal. If the
purpose is to detect a normal condition (flag is set to false is not
an exceptional situation) and bail out earlier, exceptions may not be
the right tool.

I am sure you can find more on error code checking versus exception
handling in the archives.

V
Dec 13 '05 #11

P: n/a
Peter Jansson wrote:
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method.
[snip]
Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}


Or better yet,

myFunc1(); // may throw an exception
myFunc2(); // may also throw
myFunc3(); // ditto

// ... and so on ...
// no need for try/catch in most cases; local objects are
// destroyed regardless of how control leaves the current
// block; you did use RAII consistently, right?

Dec 13 '05 #12

P: n/a
On Tue, 13 Dec 2005 16:12:02 -0500, Victor Bazarov wrote:
Jay Nabonne wrote:
On Tue, 13 Dec 2005 11:48:09 -0800, Marcelo Pinto wrote:

[snip]

is silly. 'flag' already has type 'bool', so just write

if (!flag)

I personally prefer
if(not flag)
I always have some dificulty to see the _!_ operator when I am reading
code (specially when I am in a rush, which is almost always).

What is "not" in this example?


Uh... It's a keyword, the alternative spelling for '!'. What else could
it be?


Well, my first thought was it was a Pascalian slip. :)

I've never seen "not" used in C++ code, and Visual Studio 7.1 doesn't like
it (not that that means anything). gcc does, so I guess I have learned
something new today.

Thanks.

- Jay

Dec 13 '05 #13

P: n/a

"Default User" <de***********@yahoo.com> wrote in message
news:40*************@individual.net...
Jordan wrote:
Victor,

I just wrote that for clarity for the group. Thanks.


Wrote what?


Who said that?

Mike
Dec 13 '05 #14

P: n/a
Jay Nabonne <ja*********@sonicnospam.com> wrote:
On Tue, 13 Dec 2005 16:12:02 -0500, Victor Bazarov wrote:
Jay Nabonne wrote:
What is "not" in this example?


Uh... It's a keyword, the alternative spelling for '!'. What else could
it be?


Well, my first thought was it was a Pascalian slip. :)

I've never seen "not" used in C++ code, and Visual Studio 7.1 doesn't like
it (not that that means anything). gcc does, so I guess I have learned
something new today.


On VS 7.1, you may need to #include <iso646.h> (or <ciso646> if you
prefer).

--
Marcus Kwok
Dec 13 '05 #15

P: n/a
Mike,

I was simply making a reference to Victor that originally asked my why
I displayed:

if( statement != true )

instead of

if( !statement )

I just mentioned that I normally do use '!' but I used the full
statement just for clarity purposes (also, I just finished writting
some c# code where the boolean check must be more explicit for 'true'
cases).

Dec 13 '05 #16

P: n/a
Peter,

I have to agree with Victor on this one. Typically exceptions should
only be used for worst-case scenarios. I personally like to create an
enumerated error code field and pass error codes to an error manager
which can either output to display or log the error.

Dec 13 '05 #17

P: n/a
> Mike,
I was simply making a reference to ...


oh, scratch that. I'm a gimp.

Dec 13 '05 #18

P: n/a

Jordan wrote:
Peter,

I have to agree with Victor on this one. Typically exceptions should
only be used for worst-case scenarios. I personally like to create an
enumerated error code field and pass error codes to an error manager
which can either output to display or log the error.


I'm not sure you are agreeing with Victor, but that's just my
interpretation of what you and he said.

What do you mean by "worst-case scenarios"? A system of several
different error codes (each of which presumably can from different
parts of your code) being passed around until they can be given to an
error manager to handle sounds to me like a classic case where using
exceptions could make your code cleaner and easier to read.

Gavin Deane

Dec 13 '05 #19

P: n/a
On Tue, 13 Dec 2005 22:40:45 +0000, Marcus Kwok wrote:
I've never seen "not" used in C++ code, and Visual Studio 7.1 doesn't like
it (not that that means anything). gcc does, so I guess I have learned
something new today.


On VS 7.1, you may need to #include <iso646.h> (or <ciso646> if you
prefer).


That worked. Thanks!

Dec 14 '05 #20

P: n/a
Jordan wrote:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}

Personally I prefer to return an enum value which can be given names
relevant to the result, and subsequent handling with a switch/case. This
is also useful within class definitions to help clarify the code purpose
and scope, (vital in OOAD).

JB
Dec 14 '05 #21

P: n/a
try this

do {
bool flag = myFunc1( );
if (!flag)
{
break;
}

flag = myFunc2( );
if (!flag)
{
break;
}

...
return TRUE;
} while (0);

.... // handle errors or free resources
return FALSE;
Jordan 写道:
While writing some code, I realized I had never developed a consistent
pattern for checking errors from a method. I have two styles I jump
back and forth between, but I'm wondering which is better.

Scenario:
* In method that returns success/fail
* Call method that also returns success/fail
* Need to check return state and continue or exit outer method

I personally think Case 1 looks a little cleaner but it breaks more
than case 2. Any opinions?
Case 1:

bool flag = myFunc1( );
if( flag == false )
{
return;
}

flag = myFunc2( );
if( flag == false )
{
return;
}

// more code
Case 2:

bool flag = myFunc1( );
if( flag == true )
{
flag = myFunc2( );
if( flag == true )
{
flag = myFunc3( );
if( flag == true )
{
// continue code
}
}
}


Dec 14 '05 #22

P: n/a
In my opinion the only downside to case 1 is future proofing. Clearly
the examples you have given are simple beyond real life examples. In
reality, the code would be much longer and more complex. My coding
style refuses the use of unnecessaery 'return' and/or 'break' or
'continue'.

Imaging addressing this code a few years down the line. We need to
change the code. Say both func1 and func2 must have a file opened while
they execute. Now try to add that enhancement to each of the above and
see how much longer it takes you and how many potential errors you
leave behind.

I will generally use case 2 except in unusual situations.

Paul

Dec 14 '05 #23

P: n/a
Paul,

That is a good point too. The example given is just to setup a basic
framework for suggestion. Maybe the circumstances of the question are
not good to begin with.

Let's take the example of a COM client. In COM, all methods return an
HRESULT (no exceptions here). The value of the HRESULT must be tested
before proceeding forward. When working with a COM API, it is often
common to make many linear calls to COM interface methods to initialize
an object before processing. In this case, if one of the
initialization methods errors, the parent method should bail. Using
'returns' is essential.

However, I absolutley agree that 'break' and 'continue' should be
avoided as much as possible. I have never liked those keywords - leads
to unstructured code.

Dec 14 '05 #24

P: n/a
Well, the more I think about it, my last statement wasn't completely
true - "The use of 'returns' is essential'. The nested success gate in
case 2 would still work.

Dec 14 '05 #25

P: n/a
While we are talking about it, exceptions are not ideal for basic
program control because they introduce program overhead and consume a
large amount of memory for processing. This typically is not desired
for C++ applications since we write C++ apps for performance. If you
move to another platform such as .NET, exception handling is incredidly
slow.

As far as *how* errors are handled, I like enums and mapping those to
strings. They are fast, easy to read, and consistent. True, exception
handling enhanced program readability, but ultimatley they are designed
for handling an applications "last breath" before death.

Dec 14 '05 #26

P: n/a
Jordan,
The nested success gate in case 2 would still work.

I would ALWAYS use the nested form and have been for too many years to
mention. Many times I have taken apart code of the first form and used
formal techniques to convert it to the second form, only to find the
error I sought and several others. This style will almost always find
and make clear and obvious many logic errors in the code. Method 1 is
only obfuscation with a 'you dont have to type so much' up side.

However, everyone must create their own style from their own wisdom.
Some minds would be quite capable of dealing with style 1 code. Mine
stumbles!

In my opinion, the use of returns should be avoided whenever possible,
as with break, continue and goto.

Paul

Dec 15 '05 #27

P: n/a
Geo

Victor Bazarov wrote:
Peter Jansson wrote:
[...]
Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}

Or some variant thereof.


There is a school of thought out there that strongly discourages
using exception handling to handle something that is normal. If the
purpose is to detect a normal condition (flag is set to false is not
an exceptional situation) and bail out earlier, exceptions may not be
the right tool.

I am sure you can find more on error code checking versus exception
handling in the archives.

V

Am I missing something here ? I thoght the flag was onlyset false
because an error had been detected, so it wasn't a "normal" condition ?

I'm a big fan of exceptions, use them all the time, I thought the whole
point of them was to get away from having to test return values all
over the place, and delegate error handling to the most appropriate
level in the code. Obviously it depends what you consider an error and
a "normal" condition.

Dec 15 '05 #28

P: n/a
Geo wrote:
Victor Bazarov wrote:
Peter Jansson wrote:
[...]
Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}

Or some variant thereof.
There is a school of thought out there that strongly discourages
using exception handling to handle something that is normal. If the
purpose is to detect a normal condition (flag is set to false is not
an exceptional situation) and bail out earlier, exceptions may not be
the right tool.

I am sure you can find more on error code checking versus exception
handling in the archives.

V


Am I missing something here ?


Seems like a whole lot.
I thoght the flag was onlyset false
because an error had been detected, so it wasn't a "normal" condition ?
Examples of errors:
- wrong input from the user;
- absence of a file on the external storage;
- too many sockets open at once;
- timeout while waiting for input;

Those all are _normal_ situations, happening from time to time depending
on the circumstances. Those are definitely _not_ exceptional situations
(look up "exceptional" in a dictionary). Such "errors" prevent most of
the programs to continue doing what they are asked/designed to do and need
to be handled. They are often just states of the program which simply
lead to different results than "normal", error-free, situations.

The whole point of exception handling is that if something happens down
the road (deeper in the call stack) that we do not _foresee_, try to do
our best about it. If we can _predict_ that in some course of actions it
might happen, it's not an exception.
I'm a big fan of exceptions, use them all the time, I thought the whole
point of them was to get away from having to test return values all
over the place, and delegate error handling to the most appropriate
level in the code. Obviously it depends what you consider an error and
a "normal" condition.


I think you've been duped into thinking that exceptions are a regularly
occurring thing. I strongly advise read more on the topic and review your
convictions.

V
Dec 15 '05 #29

P: n/a
Paul,

I agree. I think I better understand what you are saying. I've never
liked using 'return' statements in code, but I questioned if having
deep nestings hurt readability. However, I feel 'return' can almost be
as bad as 'goto' and should be avoided.

These are good thoughts. Thanks for everyone's input on this matter.
Let me know if you all have anymore suggestions.

Dec 15 '05 #30

P: n/a
On 2005-12-15, Jordan <jo***********@gmail.com> wrote:
Paul,

I agree. I think I better understand what you are saying.
I've never liked using 'return' statements in code, but I
questioned if having deep nestings hurt readability. However,
I feel 'return' can almost be as bad as 'goto' and should be
avoided.


I would say, use the style (nested returns, et al) that makes
what you're doing clear. If the code is easy to understand, I
wouldn't quibble about a nested return or breaks.

--
Neil Cerutti
Dec 15 '05 #31

P: n/a
Geo
Victor Bazarov wrote:
Geo wrote:
Victor Bazarov wrote:
Peter Jansson wrote:

[...]
Another track in this thread: How would instead like to use exception
handling? E.g.:

try {
myFunc1(); // Which may throw an exception if you desing it so.
myFunc2(); // Which may throw anonther exception.
myFunc3(); // Which may throw yet anonther exception.
// ... and so on
} catch(std::exception&) {
}

Or some variant thereof.

There is a school of thought out there that strongly discourages
using exception handling to handle something that is normal. If the
purpose is to detect a normal condition (flag is set to false is not
an exceptional situation) and bail out earlier, exceptions may not be
the right tool.

I am sure you can find more on error code checking versus exception
handling in the archives.

V
Am I missing something here ?


Seems like a whole lot.

> I thoght the flag was onlyset false
because an error had been detected, so it wasn't a "normal" condition ?
Examples of errors:
- wrong input from the user;
- absence of a file on the external storage;
- too many sockets open at once;
- timeout while waiting for input;

Those all are _normal_ situations, happening from time to time depending
on the circumstances. Those are definitely _not_ exceptional situations
(look up "exceptional" in a dictionary). Such "errors" prevent most of


Why look up "exceptional", maybe you should look up "exception" or
maybe "except" !!!!
the programs to continue doing what they are asked/designed to do and need
to be handled. They are often just states of the program which simply
lead to different results than "normal", error-free, situations.

The whole point of exception handling is that if something happens down
the road (deeper in the call stack) that we do not _foresee_, try to do
our best about it. If we can _predict_ that in some course of actions it
might happen, it's not an exception.
I'm a big fan of exceptions, use them all the time, I thought the whole
point of them was to get away from having to test return values all
over the place, and delegate error handling to the most appropriate
level in the code. Obviously it depends what you consider an error and
a "normal" condition.


I think you've been duped into thinking that exceptions are a regularly
occurring thing. I strongly advise read more on the topic and review your
convictions.

V

If I've been duped then it's been by Bjarne Stroustrup, C++ PL 3rd
Edition 14.1.1, last paragraph.

Looks like your definiton of exception is too dogmatic and restrictive,
you pays your money.....

Dec 15 '05 #32

P: n/a

Victor Bazarov wrote:
Examples of errors:
- wrong input from the user;
- absence of a file on the external storage;
- too many sockets open at once;
- timeout while waiting for input;

Those all are _normal_ situations, happening from time to time depending
on the circumstances. Those are definitely _not_ exceptional situations
(look up "exceptional" in a dictionary). Such "errors" prevent most of
the programs to continue doing what they are asked/designed to do and need
to be handled. They are often just states of the program which simply
lead to different results than "normal", error-free, situations.

The whole point of exception handling is that if something happens down
the road (deeper in the call stack) that we do not _foresee_, try to do
our best about it. If we can _predict_ that in some course of actions it
might happen, it's not an exception.


What about things that we do forsee and that we want to handle at this
level but that are actually detected deeper down in the call stack?

void foo
{
// do stuff
some_variable1 = helper1(params);
// do stuff
some_variable2 = helper2(params);
// do stuff
some_variable3 = helper3(params);
// do stuff
}

Suppose each of those helper functions has a similar structure, i.e.
each helper calls other functions to help it do its work. And suppose
each of those other functions calls some more. So the call stack goes a
few levels deep, with several functions at the lowest level. Some of
the functions, at every level, have non-void return types because they
need to return something to their caller. Now suppose there are some
functions at the lowest level that can detect "errors" to which the
appropriate response is to cancel the operation foo is performing. I
would handle that by throwing exceptions from the deep down functions
and catching them in foo.

The alternative is to introduce a set of error codes. Every function at
every level now has to check for errors in a return value. Previously
returned values have to become out parameters. I have a maintenance and
robustness problem because it's too easy to forget or not bother to
check an error code. The code is more cluttered with error code
checking and out parameters.

Using exceptions avoids all of those problems. Why is it relevant
whether the "errors" are things that I happen to have forseen? In fact,
I'm not really sure what it could mean to write code to handle a
situation I hadn't forseen.

Gavin Deane

Dec 16 '05 #33

P: n/a

Victor Bazarov wrote:
Those all are _normal_ situations, happening from time to time depending
on the circumstances. Those are definitely _not_ exceptional situations
(look up "exceptional" in a dictionary).
exceptional Audio pronunciation of "exceptional" ( P )
Pronunciation Key (k-spsh-nl)
adj.

1. Being an exception; uncommon.
2. Well above average; extraordinary: an exceptional memory. See
Usage Note at exceptionable.
3. Deviating widely from a norm, as of physical or mental ability:
special educational provisions for exceptional children.

exception Audio pronunciation of "exception" ( P ) Pronunciation
Key (k-spshn)
n.

1. The act of excepting or the condition of being excepted;
exclusion.
2. One that is excepted, especially a case that does not conform to
a rule or generalization.
3. An objection or a criticism: opinions that are open to exception.
4. Law. A formal objection taken in the course of an action or a
proceeding.
If we can _predict_ that in some course of actions it
might happen, it's not an exception.


I don't see anything in the definition of exceptional that states it
could not be predicted to be possible.

IMHO #2 of exception gives a good idea of its purpose in programming:
"...a case that does not conform to a rule or generalization."

So (by def of "exceptional") change your statement to: "If we can
_predict_ that in some *normal* course of actions it might happen, it's
not an exception."

For example, sometimes it is normal to hit EOF on a stream, such as
when reading a file. Other times you could consider it exceptional to
hit an EOF before hearing a terminate from that stream.

Dec 16 '05 #34

P: n/a
Victor Bazarov wrote:
The whole point of exception handling is that if something happens down
the road (deeper in the call stack) that we do not _foresee_, try to do
our best about it. If we can _predict_ that in some course of actions it
might happen, it's not an exception.


I beg to differ. For instance, new() can fail to allocate memory. This is
nothing out of the ordinary and we do forsee that this might happen from
time to time. The point of new() throwing instead of returning a special
value is not because of unpredictability but because we want the
flexibility to postpone handling of the error.
Best

Kai-Uwe Bux
Dec 16 '05 #35

P: n/a
This is splitting hairs pretty thin.
From what I understand, exceptions would be something more of a

"system-level" manner (e.g. divide by zero, unable to allocate memory,
pointer out of range, etc.).

I believe the true debate is not over the finite boundaries of
exceptions but that exceptions should not be used for routine program
control. In other words, check for ERRORS and not STATES with
exception handling.

Does this make sense?

For example, a function that opens a file in a directory passed in as a
parameter should not throw an exception if the file doesn't exist.
This would be better suited for a 'condintional' error return.
However, if the API call that opens that file barfs, an exception
should be thrown.

Dec 16 '05 #36

P: n/a
Jordan wrote:
This is splitting hairs pretty thin.
Please quote what you are refering to. If you are actually accusing me of
splitting hairs, be more specific.
From what I understand, exceptions would be something more of a

"system-level" manner (e.g. divide by zero, unable to allocate memory,
pointer out of range, etc.).


Divide by zero is unlikely to throw and so is pointer out of range. Those
conditions will usually yield undefined behavior.
I believe the true debate is not over the finite boundaries of
exceptions but that exceptions should not be used for routine program
control. In other words, check for ERRORS and not STATES with
exception handling.

Does this make sense?
Yes, in that it is a meaningful statement. It just so happens to be false or
at least a matter of opinion where reasonable can disagree. Throw-catch is
a flow control construct doing stack unwinding so that that it allows us to
break out of arbitrarily deep function call contexts. How you want to use
it, is up to you. I do not consider the distinctions of errors vs. states
(introduced by you) or predictable vs. unpredictable (suggested by Victor)
as good guidelines. I usually ask myself something like: do I want to
unwind the stack or can I handle this condition locally?
For example, a function that opens a file in a directory passed in as a
parameter should not throw an exception if the file doesn't exist.
This would be better suited for a 'condintional' error return.
However, if the API call that opens that file barfs, an exception
should be thrown.


Why? What about a constructor that constructs a file object from a file name
-- should that not throw if the file does not exists? Would you rather have
a half-constructed ill-fated object hanging around that you might not even
be able to destroy properly? In the contect of RAII, failure to acquire a
resource seems to be a good candidate for a throw() regardless of the cause
for the failure.
Best

Kai-Uwe Bux
Dec 16 '05 #37

P: n/a
Kai-Uwe Bux wrote:
Jordan wrote:
I believe the true debate is [...]

Does this make sense?

Yes, in that it is a meaningful statement. It just so happens to be false [...]


"All generalizations are wrong"
Dec 16 '05 #38

P: n/a
Jordan wrote:
For example, a function that opens a file in a directory passed in as a
parameter should not throw an exception if the file doesn't exist.


For me, the decision about how to handle that case is simple. "Am I
going to handle this situation locally?". If not, then I will avoid the
clutter of return codes (which are also at risk of not being checked)
and out parameters and throw an exception.

Gavin Deane

Dec 17 '05 #39

P: n/a
Jordan wrote:
As far as *how* errors are handled, I like enums and mapping those to
strings. They are fast, easy to read, and consistent. True, exception
handling enhanced program readability, but ultimatley they are designed
for handling an applications "last breath" before death.


Mid block gotos and returns violate structured programming. If
your constructs are small and their clearly marked you might decide
to forgive the structure violations, but you'll have to make that
decision.
Dec 17 '05 #40

P: n/a
Geo

Jordan wrote:
As far as *how* errors are handled, I like enums and mapping those to
strings. They are fast, easy to read, and consistent. True, exception
But a pain to check consistently, easily forgotten, and a mess if you
don't want to handle the error locally.
handling enhanced program readability, but ultimatley they are designed
for handling an applications "last breath" before death.


Says who ?

I prefer my applications to live a full and useful life, sudden death
is not usually part of the requirement.

Dec 19 '05 #41

P: n/a
According to MSDN Deep C++ by Robert Schmidt:

"At their core, program exceptions are conditions that arise
infrequently and unexpectedly, generally betray a program error, and
require a considered programmatic response. Failure to obey that
response often renders the affected program crippled or dead, sometimes
taking the entire system down with it. Unfortunately, crafting robust
code using traditional defensive techniques often trades one problem
(crashing exceptions) for another (more tangled design and code)."

"A software error occurs. This error may have originated as a
hardware-generated event (such as zero-divide) mapped into a software
error by a low-level driver or kernel."

"Next to outright ignoring an exception, probably the easiest response
is self-destruction. In some cases, that lazy response is actually the
correct response.

"Before you scoff, consider that some exceptions betray a condition so
severe that reasonable recovery is unlikely anyway. Perhaps the best
example is malloc of a small object returning NULL. If the free store
manager can't scrape together a few spare contiguous bytes, your
program's robustness is severely compromised, and the odds of elegant
recovery are slim."

On top of that, constructs such as COM Servers do not offer exception
handling and are dealt with via returns codes only.

I'm not suggesting exceptions have no place. Additionally, I've never
supported use of the 'goto'. I agree 100% exceptions are cleaner to
read and have the advantage of local/non-local handling. However,
exceptions do cost processing overhead and shouldn't be used for
"normal program control" (How to Program C++: 3rd Edition). If you can
handle an error locally, handle it. If not, consider if it is truly an
'error' or a 'state'.

Dec 19 '05 #42

This discussion thread is closed

Replies have been disabled for this discussion.