BorlandTalk.com Forum Index BorlandTalk.com
Borland discussion newsgroups
 
Archives   FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

exceptions vs returning null smart pointers
Goto page 1, 2  Next
 
Post new topic   Reply to topic    BorlandTalk.com Forum Index -> C++ Builder (Language C++)
View previous topic :: View next topic  
Author Message
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 1:27 am    Post subject: exceptions vs returning null smart pointers Reply with quote



I know that the debate between exceptions and return values will never
end, but I'm in a case where my functions return smart pointers.

What method would you suggest I take to indicate failure.

return boost::smart_ptr<TVSSocketInfo>( NULL );

or

throw Exception("");

Thank you.

Jonathan



Back to top
Hendrik Schober
Guest





PostPosted: Thu Jun 23, 2005 9:49 am    Post subject: Re: exceptions vs returning null smart pointers Reply with quote



Jonathan Benedicto <incorrect (AT) no (DOT) server> wrote:
Quote:
[...]
What method would you suggest I take to indicate failure.

return boost::smart_ptr<TVSSocketInfo>( NULL );

or

throw Exception("");

This depends. Really, you need to supply more
context.

Quote:
Thank you.

Jonathan


Schobi

--
[email]SpamTrap (AT) gmx (DOT) de[/email] is never read
I'm Schobi at suespammers dot org

"Coming back to where you started is not the same as never leaving"
Terry Pratchett



Back to top
Chris Uzdavinis (TeamB)
Guest





PostPosted: Thu Jun 23, 2005 1:47 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote



"Jonathan Benedicto" <incorrect (AT) no (DOT) server> writes:

Quote:
I know that the debate between exceptions and return values will never
end, but I'm in a case where my functions return smart pointers.

What method would you suggest I take to indicate failure.

return boost::smart_ptr<TVSSocketInfo>( NULL );

or

throw Exception("");

That depends. (You didn't expect a different answer did you? <g>)

What semantics do you want? Is it meaningful to every have null smart
pointers? If so, or you're willing to take the responsibility to
check each and every one, then return null smart pointers.

Alternately, an exception is not easily ignored. It must be dealt
with, and thus the user cannot silently, continue into the function in
spite of an error. Thus, if you write code that works in the presence
of exceptions, this is probably preferable. (And writing code that
works in the presence of exceptions is highly desirable for multiple
reasons, including 1) exceptions really do happen, so you want your
code to work 2) oftentimes, and somewhat surprisingly, the overall
quality of your code improves, such that other types of non-exception
bugs are also cleaned up by thinking about exceptions.

So I encourage you to use exceptions, and to learn the nuances
involved with writing code that works correctly with exceptions.
(Herb Sutter's "Exceptional C++" is a good place to start.)

--
Chris (TeamB);

Back to top
Liz Albin
Guest





PostPosted: Thu Jun 23, 2005 3:35 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

On Wed, 22 Jun 2005 21:27:26 -0400, Jonathan Benedicto wrote:

Quote:
What method would you suggest I take to indicate failure.

Here's a third "that depends"

For example:

If the result of a failure in your routine is that the whole application
should fail, and you need to report that -- an exception might be the way
to go,

On the other hand, if the result of a failure of this routine is simply
that an optional object is unavailable (for example, that some data are
locked and the current user can't write to them) you might prefer /not/
terminating the application.

Perhaps if the application doesn't require user interaction, you should be
logging this stuff and going on.

So again, the answer is "it depends"
--
Good luck,

liz

Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 3:36 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Hendrik Schober" <SpamTrap (AT) gmx (DOT) de> wrote

Quote:
This depends. Really, you need to supply more
context.

Sorry. I'll try and give more detail.

In this particular project, a class handles a list of socket
structures. This class stores the structures in a vector, and has a

__property TVSSocketInfoPtr Sockets[DWORD Index] = { read =
GetSockets( DWORD Index ) };

where TVSSocketInfoPtr is a typedef boost::shared_ptr<TVSSocketInfo>
TVSSocketInfoPtr.

In the GetSockets function, it checks to see if the Index is out of
range. If it is, it must somehow return a error.

So, this is where my question is. Should I use this method:

TVSSocketInfoPtr __fastcall TVSSocketList::GetSockets(DWORD Index)
{
// The server has requested a specific socket info structure
from the vector.
TVSSocketInfoPtr SocketInfo = NULL;

// Check that the supplied index is within the range of the
vector.
if( Index >= 0 && Index < FSockets.size() )
{
// And if it is, find, lock and return the structure.
// ....
}
else
{
// The index was out of range, so throw an exception.
throw EVSReturningNull();
}
}

Or

TVSSocketInfoPtr __fastcall TVSSocketList::GetSockets(DWORD Index)
{
// The server has requested a specific socket info structure
from the vector.
TVSSocketInfoPtr SocketInfo = NULL;

// Check that the supplied index is within the range of the
vector.
if( Index >= 0 && Index < FSockets.size() )
{
// And if it is, find, lock and return the structure.
// ....
}
else
{
// The index was out of range, so return a NULL.
return TVSSocketInfo( NULL );
}
}

I hope that this is clearer.

Jonathan



Back to top
Alan Bellingham
Guest





PostPosted: Thu Jun 23, 2005 3:41 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

Liz Albin <lizalbin (AT) yahooNotThis (DOT) com> wrote:

Quote:
Here's a third "that depends"

For example:

If the result of a failure in your routine is that the whole application
should fail, and you need to report that -- an exception might be the way
to go,

On the other hand, if the result of a failure of this routine is simply
that an optional object is unavailable (for example, that some data are
locked and the current user can't write to them) you might prefer /not/
terminating the application.

So an exception again. Which you catch at the point that knows how to
retry, ignore, or give up.

Quote:
Perhaps if the application doesn't require user interaction, you should be
logging this stuff and going on.

Which an exception could allow you to do, at a level where the code
knows what's really going on (so, not "Failed to read 2 bytes", but more
"Failed to read 2 bytes from important configuration data file".

Quote:
So again, the answer is "it depends"

Yep.

Alan Bellingham
--
Me <url:mailto:alanb (AT) episys (DOT) com> <url:http://www.doughnut.demon.co.uk/>
ACCU - C, C++ and Java programming <url:http://accu.org/>
The 2004 Discworld Convention <url:http://dwcon.org/>

Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 3:41 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Chris Uzdavinis (TeamB)" <chris (AT) uzdavinis (DOT) com> wrote

Quote:
That depends. (You didn't expect a different answer did you? <g>)

I think that I wanted to get pros and cons of either method and then
take the best route. But I guess that it is very context dependant.

Quote:
What semantics do you want? Is it meaningful to every have null
smart
pointers? If so, or you're willing to take the responsibility to
check each and every one, then return null smart pointers.

Alternately, an exception is not easily ignored. It must be dealt
with, and thus the user cannot silently, continue into the function
in
spite of an error. Thus, if you write code that works in the
presence
of exceptions, this is probably preferable. (And writing code that
works in the presence of exceptions is highly desirable for multiple
reasons, including 1) exceptions really do happen, so you want your
code to work 2) oftentimes, and somewhat surprisingly, the overall
quality of your code improves, such that other types of
non-exception
bugs are also cleaned up by thinking about exceptions.

So I encourage you to use exceptions, and to learn the nuances
involved with writing code that works correctly with exceptions.
(Herb Sutter's "Exceptional C++" is a good place to start.)

Thank you for this reference. I personally have always preferred
exceptions to returning NULL's etc. When I discovered exceptions, it
really made my programming style much cleaner.

In this context, I really prefer:

try {
SocketInfo = SocketList->Sockets[ 0 ];
} catch( const EVSReturningNull &E )
// ...
}

to

SocketInfo = SocketList->Sockets[ 0 ];
if( SocketInfo.get() )
{
// ...

Jonathan



Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 3:44 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Liz Albin" <lizalbin (AT) yahooNotThis (DOT) com> wrote

Quote:
Here's a third "that depends"

Thank you. At least I'm building up pros and cons for both sides at
once. <g>

Quote:
For example:

If the result of a failure in your routine is that the whole
application
should fail, and you need to report that -- an exception might be
the way
to go,

On the other hand, if the result of a failure of this routine is
simply
that an optional object is unavailable (for example, that some data
are
locked and the current user can't write to them) you might prefer
/not/
terminating the application.

Perhaps if the application doesn't require user interaction, you
should be
logging this stuff and going on.

So again, the answer is "it depends"

If I did use exceptions, I'd use a EVSReturningNull exception to
report a non-critical exception, and my try / catch would only catch
those. If a different exception was thrown, then it would be caught by
another try / catch that catches all the exceptions, logs them, and
terminates the app.

Jonathan



Back to top
Chris Uzdavinis (TeamB)
Guest





PostPosted: Thu Jun 23, 2005 3:48 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Jonathan Benedicto" <incorrect (AT) no (DOT) server> writes:

Quote:
In the GetSockets function, it checks to see if the Index is out of
range. If it is, it must somehow return a error.

Usually, I think of exceptions as an indicator of runtime errors that
are a normal part of running an application.

Further, out-of-bounds indicies are considered programming bugs, not
exceptions. Thus, assertions should catch those. Invalid indicies
should never be calculated.

The only time where an out-of-bounds may be acceptible at runtime is
when receiving data from an unknown source. Thus, at your software's
"edge" you take data and validate it then. At the perimeter, it's
ok to check for invalid data and throw an exception if it fails.
However, once it's accepted into your subsystem's inner circle, it
should always be valid.

I found that most exceptions relate to invalid input or other
externally-imposed problems (out of disk space, etc.) I also find
that most try-catch blocks are around the outermost functions in my
subsystem's interface. That is, between each subsystem in a program
is a good place to catch exceptions and log/report/translate them into
a meaningful error to report to the calling code.

--
Chris (TeamB);

Back to top
Chris Uzdavinis (TeamB)
Guest





PostPosted: Thu Jun 23, 2005 3:54 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Jonathan Benedicto" <incorrect (AT) no (DOT) server> writes:

Quote:
Thank you for this reference. I personally have always preferred
exceptions to returning NULL's etc. When I discovered exceptions, it
really made my programming style much cleaner.

Sure, it's a fantastic book, even for the other topics it covers.

Quote:

In this context, I really prefer:

try {
SocketInfo = SocketList->Sockets[ 0 ];
} catch( const EVSReturningNull &E )
// ...
}

Ironically, I find that the better exception-safe code uses FEWER
try-catch blocks. When possible, an exception shoud unwind the stack
to the main 'loop'. That is, each time the main loop starts calling
into functions and making the stack get some depth, it's all for ONE
operation, and if it fails, we want to unroll the whole stack back to
the main loop, and report a failure, then iterate again.

This means that the main loop makes its call with a try-catch block
protecting it, but that most of the code it calls into does NOT catch
exceptions, it only produces them.

However, if your fucnctions that do the "work" end up calling into
another library that produces many exceptions, perhaps you'll need to
catch those, but sometimes even then you won't.

The real trick, then, is to ensure that your program properly cleans
up when your stack unwinds due to an exception.

That's also why I like exceptions to indicate that the failure is not
something trivial, but aborts the current operation.

--
Chris (TeamB);

Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 4:00 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Chris Uzdavinis (TeamB)" <chris (AT) uzdavinis (DOT) com> wrote

Quote:
Usually, I think of exceptions as an indicator of runtime errors
that
are a normal part of running an application.

Further, out-of-bounds indicies are considered programming bugs, not
exceptions. Thus, assertions should catch those. Invalid indicies
should never be calculated.

The only time where an out-of-bounds may be acceptible at runtime is
when receiving data from an unknown source. Thus, at your
software's
"edge" you take data and validate it then. At the perimeter, it's
ok to check for invalid data and throw an exception if it fails.
However, once it's accepted into your subsystem's inner circle, it
should always be valid.

Would you consider the value received from GetQueuedCompletionStatus
in the dwCompletionKey parameter an unknown source ? <g>



Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 4:03 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Chris Uzdavinis (TeamB)" <chris (AT) uzdavinis (DOT) com> wrote

Quote:
Ironically, I find that the better exception-safe code uses FEWER
try-catch blocks. When possible, an exception shoud unwind the
stack
to the main 'loop'. That is, each time the main loop starts calling
into functions and making the stack get some depth, it's all for ONE
operation, and if it fails, we want to unroll the whole stack back
to
the main loop, and report a failure, then iterate again.

This means that the main loop makes its call with a try-catch block
protecting it, but that most of the code it calls into does NOT
catch
exceptions, it only produces them.

However, if your fucnctions that do the "work" end up calling into
another library that produces many exceptions, perhaps you'll need
to
catch those, but sometimes even then you won't.

The real trick, then, is to ensure that your program properly cleans
up when your stack unwinds due to an exception.

That's also why I like exceptions to indicate that the failure is
not
something trivial, but aborts the current operation.

In this case, if the function fails, then the app must just ignore the
work "chunk" that GetQueuedCompletionStatus retuned, and the app must
skip the rest of the code in the loop and go back to
GetQueuedCompletionStatus.

For all other exceptions, they are logged, and the loop exits.

Jonathan



Back to top
Chris Uzdavinis (TeamB)
Guest





PostPosted: Thu Jun 23, 2005 4:09 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Jonathan Benedicto" <incorrect (AT) no (DOT) server> writes:

Quote:
Would you consider the value received from GetQueuedCompletionStatus
in the dwCompletionKey parameter an unknown source ?

I'm not sure what a queued completion status is, but if it's from user
input, then yes. Or, if you're writing a library and the value is
passed in by a caller that you cannot control, then again, yes.

But if you generate the data internally, then you trust your code
works and honors your requirements, and so whenever the "impossible"
has occurred in that case, it means there is a programming bug that
needs fixing, and not a normal runtime error.

--
Chris (TeamB);

Back to top
Jonathan Benedicto
Guest





PostPosted: Thu Jun 23, 2005 4:21 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Chris Uzdavinis (TeamB)" <chris (AT) uzdavinis (DOT) com> wrote

Quote:
I'm not sure what a queued completion status is, but if it's from
user
input, then yes. Or, if you're writing a library and the value is
passed in by a caller that you cannot control, then again, yes.

But if you generate the data internally, then you trust your code
works and honors your requirements, and so whenever the "impossible"
has occurred in that case, it means there is a programming bug that
needs fixing, and not a normal runtime error.

The value should be from my code, but I've had unexpected values
returned by this function, so I can't take any chances.

Jonathan



Back to top
Chris Uzdavinis (TeamB)
Guest





PostPosted: Thu Jun 23, 2005 4:39 pm    Post subject: Re: exceptions vs returning null smart pointers Reply with quote

"Jonathan Benedicto" <incorrect (AT) no (DOT) server> writes:

Quote:
The value should be from my code, but I've had unexpected values
returned by this function, so I can't take any chances.

Ok, but that means you need more assertions, to track the errors to
their soruce. Writing code that "deals with" bugs by working around
problems that should not happen is simply going out of your way to
make it harder to find the bugs, and to make it easier to write them.

Make a bug-hostile environment, not a bug-friendly environment. When
you get strict with your data, the problems are detected earlier and
often closer to the bug. With a formitable wall of assertions, bad
data won't get through your code, and then you can trust your data.

If an assertion fails, wither the assertion's test is wrong, or it
caught a real bug. Add more assertions earlier in the code path and
trace it back. Leave the assertions in, to prevent future
repetations.

--
Chris (TeamB);

Back to top
Display posts from previous:   
Post new topic   Reply to topic    BorlandTalk.com Forum Index -> C++ Builder (Language C++) All times are GMT
Goto page 1, 2  Next
Page 1 of 2

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2006 phpBB Group
SEO toolkit © 2004-2006 webmedic.