Throwing Exceptions

  • Follow


Do people often use exceptions by choice in C++?  I can't think of much 
I'd do with them that I couldn't do with return values, but they do seem 
to complicate things by providing a second error-checking procedure that 
some functions or classes will use but others won't.

-- 
"A good plan executed right now is far better than a perfect plan
executed next week."
                       -Gen. George S. Patton
0
Reply glhansen (396) 4/22/2005 7:20:32 PM


"Gregory L. Hansen" wrote:
> 
> Do people often use exceptions by choice in C++?  I can't think of much
> I'd do with them that I couldn't do with return values, but they do seem
> to complicate things by providing a second error-checking procedure that
> some functions or classes will use but others won't.
> 

try...catch clauses are syntactically cleaner in many cases. For
example, suppose you have 10 functions to be called, each possibly
generating an error flag (or throwing an exception).
If you throw exceptions, you can do this:
   try (
      a = fun1(...); 
      b = fun2(...); 
      c = fun3(...); 
      d = fun4(...); 
      e = fun5(...); 
      f = fun6(...); 
      g = fun7(...); 
      h = fun8(...); 
      i = fun9(...); 
      j = fun10(...); 
   }
   catch ...
   {
      ...
   }

Using flags, you have to put "if" or "switch" statements after every
function call and check there - very tedious:
  a = fun1(...);
  switch ( a ) {
  case ERROR1:
    ...
    break;
  case ERROR2:
    ...
    break;
  default:
    b = fun2(...);
    if ( b == 0 ) {
       ...
    }
    ...
  }
-- 
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Common User Interface Services
M/S 2R-94  (206)544-5225
0
Reply fred.l.kleinschmidt2 (73) 4/22/2005 8:31:26 PM


On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:

>
>Do people often use exceptions by choice in C++?  I can't think of much 
>I'd do with them that I couldn't do with return values, but they do seem 
>to complicate things by providing a second error-checking procedure that 
>some functions or classes will use but others won't.

I think real C++ programmers use exceptions all the time. It makes
code much easier to read as well as allows special error handling.
Since STL throws exceptions so catching these is also essential.

Please show an example where you think return values are better.

/ajk



--
"I never forget a face, but in your case I'll be glad to make an exception."
Groucho Marx.
0
Reply ajk 4/23/2005 8:03:05 AM

In article <520k611j9b098nvho251p6jo41rk9a9dsh@4ax.com>,
ajk  <gandalf<at> wrote:
>On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
>glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:
>
>>
>>Do people often use exceptions by choice in C++?  I can't think of much 
>>I'd do with them that I couldn't do with return values, but they do seem 
>>to complicate things by providing a second error-checking procedure that 
>>some functions or classes will use but others won't.
>
>I think real C++ programmers use exceptions all the time. It makes
>code much easier to read as well as allows special error handling.
>Since STL throws exceptions so catching these is also essential.
>
>Please show an example where you think return values are better.

I'm pretty sure I didn't say that I think return values are better, except 
in the sense of the complication of sometimes using one type of error 
checking and sometimes using another.

Let me rephrase the question.  What do people do with exceptions, which 
they couldn't do with return values, that makes code easier to read and 
allows special error handling?


-- 
"A good plan executed right now is far better than a perfect plan
executed next week."
                       -Gen. George S. Patton
0
Reply glhansen (396) 4/23/2005 5:07:32 PM

Gregory L. Hansen wrote:
> Do people often use exceptions by choice in C++?

No.  Here's lots of reasons why.

1) Exceptions are sporadically used by 3rd party libraries and 
frameworks.  With the exception of the STL and probably Boost, I haven't 
seen any library or third party framework that is designed to take 
advantage of exceptions consistently.

2) C++ permits code to throw exceptions without declaring them; 
exception safety isn't enforced by the compiler as strongly as in, say, 
Java.

3) The STL isn't guaranteed exception-safe in lots of important places, 
like containers.

4) C++ compilers do not consistently implement exceptions.  For example, 
last I checked, Visual C++ will return NULL instead of throwing a 
bad_alloc exception (as required by the standard) if new fails.  This 
makes exceptions more difficult to include in portable code.

5) C++ exceptions are not widely understood.  This vicious cycle means 
that writing C++ code with exceptions reduces the pool of programmers 
who can maintain it.

6) C++ exceptions on most implementations cause a performance hit, even 
if no exception is thrown.

7) C++ exceptions are extraordinarily difficult to reason about.  For 
example, consider the seemingly simple problem, as posed by Herb Sutter 
(who sits on the C++ standard committee), of writing an exception safe 
stack.

http://www.gotw.ca/gotw/008.htm

His solution turned out to be 1) not entirely correct and 2) not 
compileable by any compiler he had.  Nasty!

> I can't think of much 
> I'd do with them that I couldn't do with return values

Some people say that exceptions are better than return values because 
return values indicating errors are often ignored, leading to undefined 
behavior, and exceptions at least "force something to happen."  Others 
disagree; this is one of those religous issues where you should make up 
your own mind.

Exceptions can also be used for flow control, as seen in other responses 
to your post.

>, but they do seem 
> to complicate things by providing a second error-checking procedure that 
> some functions or classes will use but others won't.

Exceptions are part of the specification of a class or function, and 
need to be considered during the design instead of tacked on afterwards. 
  You're right that they complicate things and are less useful if not 
used consistently, but they let you indicate errors much more cleanly 
than many of the hacks in wide use (like errno).

-Peter

-- 
Pull out a splinter to reply.
0
Reply gershwin (187) 4/24/2005 12:17:39 AM

"Gregory L. Hansen" wrote:
>
> Do people often use exceptions by choice in C++?  I can't think of
> much I'd do with them that I couldn't do with return values, but they 
> do seem to complicate things by providing a second error-checking 
> procedure that some functions or classes will use but others won't.

There's an alternative to throwing exceptions or using return values for
handling exceptional conditions and that is using state machines. If a
state machine encounters an exceptional condition, it can transition
into an error state. Part of the action it takes is to notify other
state machines about this event. The other state machines can then take
whatever action is appropriate.

This model is especially useful in a multithreaded environment. If an
exception is thrown from one thread, it may wind its way all the way
through the application without being caught, not to mention that if
care is not take, it could leave the object throwing the exception in an
indeterminate state. State machines notifying each other through events
ensures that this is not a problem.

In addition, this approach has an advantage over return values. When you
call a method, you often want to "fire and forget." You call the method
and go about your business. If an exceptional condition arises, the
event model takes care of letting you know about it.

I am currently writing in C#. Throwing exceptions is the norm for
handling error conditions in the .NET Framework. There is, however, a
few instances where events are used instead. I wish it were the other
way around.



0
Reply jabberdabber3 (156) 4/24/2005 12:57:18 AM

Gregory L. Hansen coughed up:
> In article <520k611j9b098nvho251p6jo41rk9a9dsh@4ax.com>,
> ajk  <gandalf<at> wrote:
>> On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
>> glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:
>>
>>>
>>> Do people often use exceptions by choice in C++?  I can't think of
>>> much I'd do with them that I couldn't do with return values, but
>>> they do seem to complicate things by providing a second
>>> error-checking procedure that some functions or classes will use
>>> but others won't.
>>
>> I think real C++ programmers use exceptions all the time. It makes
>> code much easier to read as well as allows special error handling.
>> Since STL throws exceptions so catching these is also essential.
>>
>> Please show an example where you think return values are better.
>
> I'm pretty sure I didn't say that I think return values are better,
> except in the sense of the complication of sometimes using one type
> of error checking and sometimes using another.
>
> Let me rephrase the question.  What do people do with exceptions,
> which they couldn't do with return values, that makes code easier to
> read and allows special error handling?


If you are passing error conditions around by return values, then 
essentially every function call becomes part of an if() statement.  This 1. 
becomes cluttered, and 2. in the calling sequence: a()->b()->c(), it's 
likely that c()'s error returns will get converted over to b()'s so that b() 
can return some error condition to a().

When you are using exceptions, then (ideally) you would have only the part 
of the code that recognizes the error condition do something about it by 
throwing an exception.  The stack of function calls up to that point need 
not have a single check for return value "status".


-- 
http://www.allexperts.com is a nifty way to get an answer to just about
/anything/.


0
Reply tgm2tothe10thpower (2065) 4/24/2005 2:39:47 AM

Hi,

<skip>

> 4) C++ compilers do not consistently implement exceptions.
> For example, last I checked, Visual C++ will return NULL
> instead of throwing a bad_alloc exception (as required by the
> standard) if new fails.  This makes exceptions more difficult
> to include in portable code.

I've tested the following snippet with vc.net 2003 right after
read you post:

#include <iostream>
#include <limits>
#include <stdexcept>

using namespace std;

void main()
{
	size_t how_many	=	numeric_limits<size_t>::max();
	try
	{
		double* pdbl	=	new double[how_many-1];
		if ( !pdbl )
                      throw logic_error("new returned null!");
		delete[] pdbl;
	}
	catch ( const logic_error& le )
	{
		cout << le.what();
	}
	catch ( const exception& e )
	{
	    cout << e.what();
	}
	catch ( ... )
	{
		cout << "strange shit happend!";
	}
}

bad allocation was the output so new throws std::bad_alloc now.

<skip>
0
Reply suralis-s (31) 4/24/2005 10:01:15 AM

In article <TFDae.2523$Sk6.982@trndny08>,
Thomas G. Marshall <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> wrote:
>Gregory L. Hansen coughed up:
>> In article <520k611j9b098nvho251p6jo41rk9a9dsh@4ax.com>,
>> ajk  <gandalf<at> wrote:
>>> On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
>>> glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:
>>>
>>>>
>>>> Do people often use exceptions by choice in C++?  I can't think of
>>>> much I'd do with them that I couldn't do with return values, but
>>>> they do seem to complicate things by providing a second
>>>> error-checking procedure that some functions or classes will use
>>>> but others won't.
>>>
>>> I think real C++ programmers use exceptions all the time. It makes
>>> code much easier to read as well as allows special error handling.
>>> Since STL throws exceptions so catching these is also essential.
>>>
>>> Please show an example where you think return values are better.
>>
>> I'm pretty sure I didn't say that I think return values are better,
>> except in the sense of the complication of sometimes using one type
>> of error checking and sometimes using another.
>>
>> Let me rephrase the question.  What do people do with exceptions,
>> which they couldn't do with return values, that makes code easier to
>> read and allows special error handling?
>
>
>If you are passing error conditions around by return values, then 
>essentially every function call becomes part of an if() statement.  This 1. 
>becomes cluttered, and 2. in the calling sequence: a()->b()->c(), it's 
>likely that c()'s error returns will get converted over to b()'s so that b() 
>can return some error condition to a().
>
>When you are using exceptions, then (ideally) you would have only the part 
>of the code that recognizes the error condition do something about it by 
>throwing an exception.  The stack of function calls up to that point need 
>not have a single check for return value "status".

I suppose that's most useful when declaring a new object from a class 
which may be derived from any number of other classes and needs to 
allocate memory at any level in the ancestry.  Then use a single try{} and 
catch(NOT_ENOUGH_MEMORY){} at the top.

I'd imagined using it at a more direct level, like

try{function1()}
catch(oops){recover1()}
try{function2()}
catch(oops){recover2()}
try{function3()}
catch(oops){recover3()}

which would really be no different than making each function call part of 
an if() statement.

-- 
"Let us learn to dream, gentlemen, then perhaps we shall find the
truth... But let us beware of publishing our dreams before they have been
put to the proof by the waking understanding." -- Friedrich August Kekul�
0
Reply glhansen (396) 4/24/2005 12:30:37 PM

In article <1-ydnTOLaec4ePffRVn-jg@comcast.com>,
Peter Ammon  <gershwin@splintermac.com> wrote:
>Gregory L. Hansen wrote:
>> Do people often use exceptions by choice in C++?
>
>No.  Here's lots of reasons why.

Okay, so it's not just me.

Here's another question.  *Should* people often use exceptions?

I'm thinking analogously to STL.  Someone on this group (I forget who and 
I don't really want to quit this post and track him down) had said that 
STL encourages some good coding practices, and that STL users can tell 
non-STL users by the way they code even outside of C++.

Are exceptions good for me, even if I don't want to admit it?
-- 
"When the fool walks through the street, in his lack of understanding he 
calls everything foolish." -- Ecclesiastes 10:3, New American Bible
0
Reply glhansen (396) 4/24/2005 12:35:41 PM

Gregory L. Hansen coughed up:
> In article <TFDae.2523$Sk6.982@trndny08>,
> Thomas G. Marshall
> <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> wrote:
>> Gregory L. Hansen coughed up:
>>> In article <520k611j9b098nvho251p6jo41rk9a9dsh@4ax.com>,
>>> ajk  <gandalf<at> wrote:
>>>> On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
>>>> glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:
>>>>
>>>>>
>>>>> Do people often use exceptions by choice in C++?  I can't think of
>>>>> much I'd do with them that I couldn't do with return values, but
>>>>> they do seem to complicate things by providing a second
>>>>> error-checking procedure that some functions or classes will use
>>>>> but others won't.
>>>>
>>>> I think real C++ programmers use exceptions all the time. It makes
>>>> code much easier to read as well as allows special error handling.
>>>> Since STL throws exceptions so catching these is also essential.
>>>>
>>>> Please show an example where you think return values are better.
>>>
>>> I'm pretty sure I didn't say that I think return values are better,
>>> except in the sense of the complication of sometimes using one type
>>> of error checking and sometimes using another.
>>>
>>> Let me rephrase the question.  What do people do with exceptions,
>>> which they couldn't do with return values, that makes code easier to
>>> read and allows special error handling?
>>
>>
>> If you are passing error conditions around by return values, then
>> essentially every function call becomes part of an if() statement.
>> This 1. becomes cluttered, and 2. in the calling sequence:
>> a()->b()->c(), it's likely that c()'s error returns will get
>> converted over to b()'s so that b() can return some error condition
>> to a().
>>
>> When you are using exceptions, then (ideally) you would have only
>> the part of the code that recognizes the error condition do
>> something about it by throwing an exception.  The stack of function
>> calls up to that point need not have a single check for return value
>> "status".
>
> I suppose that's most useful when declaring a new object from a class
> which may be derived from any number of other classes and needs to
> allocate memory at any level in the ancestry.  Then use a single
> try{} and catch(NOT_ENOUGH_MEMORY){} at the top.
>
> I'd imagined using it at a more direct level, like
>
> try{function1()}
> catch(oops){recover1()}
> try{function2()}
> catch(oops){recover2()}
> try{function3()}
> catch(oops){recover3()}
>
> which would really be no different than making each function call
> part of
> an if() statement.


Well, in general that's an example of what I'd consider to be fairly badly 
organized code.

You try to centralize as much as possible the catching of exceptions, so 
long as there's no reason to keep a catch local to a particular area.

Typically it would be more like this in calling order

    catch the exceptions for:
        a()
            b()
                c()
                return from c()
                c2()
                return from c2()
                    d()
                    return from d()
            return from b()
        return from a()

Now anywhere in the hierarchy a throw can occur, and /none/ of the calls 
need to have an individual check, and certainly not an individual catch for 
each call.


-- 
Forgetthesong,I'dratherhavethefrontallobotomy...


0
Reply tgm2tothe10thpower (2065) 4/24/2005 2:01:13 PM

Thomas G. Marshall coughed up:
> Gregory L. Hansen coughed up:
>> In article <TFDae.2523$Sk6.982@trndny08>,
>> Thomas G. Marshall
>> <tgm2tothe10thpower@replacetextwithnumber.hotmail.com> wrote:
>>> Gregory L. Hansen coughed up:
>>>> In article <520k611j9b098nvho251p6jo41rk9a9dsh@4ax.com>,
>>>> ajk  <gandalf<at> wrote:
>>>>> On Fri, 22 Apr 2005 19:20:32 +0000 (UTC),
>>>>> glhansen@steel.ucs.indiana.edu (Gregory L. Hansen) wrote:
>>>>>
>>>>>>
>>>>>> Do people often use exceptions by choice in C++?  I can't think
>>>>>> of much I'd do with them that I couldn't do with return values,
>>>>>> but they do seem to complicate things by providing a second
>>>>>> error-checking procedure that some functions or classes will use
>>>>>> but others won't.
>>>>>
>>>>> I think real C++ programmers use exceptions all the time. It makes
>>>>> code much easier to read as well as allows special error handling.
>>>>> Since STL throws exceptions so catching these is also essential.
>>>>>
>>>>> Please show an example where you think return values are better.
>>>>
>>>> I'm pretty sure I didn't say that I think return values are better,
>>>> except in the sense of the complication of sometimes using one type
>>>> of error checking and sometimes using another.
>>>>
>>>> Let me rephrase the question.  What do people do with exceptions,
>>>> which they couldn't do with return values, that makes code easier
>>>> to read and allows special error handling?
>>>
>>>
>>> If you are passing error conditions around by return values, then
>>> essentially every function call becomes part of an if() statement.
>>> This 1. becomes cluttered, and 2. in the calling sequence:
>>> a()->b()->c(), it's likely that c()'s error returns will get
>>> converted over to b()'s so that b() can return some error condition
>>> to a().
>>>
>>> When you are using exceptions, then (ideally) you would have only
>>> the part of the code that recognizes the error condition do
>>> something about it by throwing an exception.  The stack of function
>>> calls up to that point need not have a single check for return value
>>> "status".
>>
>> I suppose that's most useful when declaring a new object from a class
>> which may be derived from any number of other classes and needs to
>> allocate memory at any level in the ancestry.  Then use a single
>> try{} and catch(NOT_ENOUGH_MEMORY){} at the top.
>>
>> I'd imagined using it at a more direct level, like
>>
>> try{function1()}
>> catch(oops){recover1()}
>> try{function2()}
>> catch(oops){recover2()}
>> try{function3()}
>> catch(oops){recover3()}
>>
>> which would really be no different than making each function call
>> part of
>> an if() statement.
>
>
> Well, in general that's an example of what I'd consider to be fairly
> badly organized code.
>
> You try to centralize as much as possible the catching of exceptions,
> so long as there's no reason to keep a catch local to a particular
> area.
> Typically it would be more like this in calling order
>
>    catch the exceptions for:
>        a()
>            b()
>                c()
>                return from c()
>                c2()
>                return from c2()
>                    d()
>                    return from d()
>            return from b()
>        return from a()

Not that it matters, but in my usually dumb haste, I goofed the nesting:

    catch the exceptions for:
        a()
            b()
                c()
                return from c()
                c2()
                    d()
                    return from d()
                return from c2()
            return from b()
        return from a()


>
> Now anywhere in the hierarchy a throw can occur, and /none/ of the
> calls need to have an individual check, and certainly not an
> individual catch for each call.



-- 
Forgetthesong,I'dratherhavethefrontallobotomy...


0
Reply tgm2tothe10thpower (2065) 4/24/2005 2:03:13 PM

Gregory L. Hansen coughed up:
> In article <1-ydnTOLaec4ePffRVn-jg@comcast.com>,
> Peter Ammon  <gershwin@splintermac.com> wrote:
>> Gregory L. Hansen wrote:
>>> Do people often use exceptions by choice in C++?
>>
>> No.  Here's lots of reasons why.
>
> Okay, so it's not just me.
>
> Here's another question.  *Should* people often use exceptions?
>
> I'm thinking analogously to STL.  Someone on this group (I forget who
> and I don't really want to quit this post and track him down) had
> said that STL encourages some good coding practices, and that STL
> users can tell non-STL users by the way they code even outside of C++.
>
> Are exceptions good for me, even if I don't want to admit it?


You should have 3 a day.  With water.

-- 
Forgetthesong,I'dratherhavethefrontallobotomy...


0
Reply tgm2tothe10thpower (2065) 4/24/2005 2:06:08 PM

Gregory L. Hansen wrote:

> In article <1-ydnTOLaec4ePffRVn-jg@comcast.com>,
> Peter Ammon  <gershwin@splintermac.com> wrote:
>>Gregory L. Hansen wrote:
>>> Do people often use exceptions by choice in C++?
>>
>>No.  Here's lots of reasons why.
> 
> Okay, so it's not just me.
> 
> Here's another question.  *Should* people often use exceptions?
> 
> I'm thinking analogously to STL.  Someone on this group (I forget who and
> I don't really want to quit this post and track him down) had said that
> STL encourages some good coding practices, and that STL users can tell
> non-STL users by the way they code even outside of C++.
> 
> Are exceptions good for me, even if I don't want to admit it?

There was a fairly long and heated Thead on comp.lang.c++.moderated recently
about the pro and cons of exceptions. Try to find it in the Archives, if
you are interested in it.

Exceptions have a few points to be aware of, and programming in an exception
save way is not trivial (but not unmasterably difficult).
It takes a bit to getting used to writing an exception save code, but the
effort is well worth it, since these techniques increase your overall code
quality.
BUT: The same problems apply to other error catching mecanisms as well.
The uncomfortable truth is, writing programms that deal well with
exceptional situations is hard.

The question to ask is not should I use exceptions, but what do I have to do
if I don't use them?

The main problems of exceptional situations is that they are well
exceptional. You don't except them. Or put differently, you have to be
constantly on the watch.

Consider the following function:

void doSomethingDifficult() {

  ObjectWhichHoldsResorces resorce;

  doStep1(resorce);
  doStep2(resorce);
  doStep3(resorce);
  doStep4(resorce);

  return;
}

With exceptions this is fine. It does the right thing, no matter where the
exceptional situation occurs. Explicit error checking makes no sense here,
too, since doSomethingDifficult() has no more information than the
underfunctions. look at the same thing with return values.

ErrorObject doSomethingDifficult() {

  ErrorObject error(NO_ERROR);
  ObjectWhichHoldsResorces resorce;
  
  error = doStep1(resorce);
  if (error()) {
        return error;
  }
  doStep2(resorce);
  if (error()) {
        return error;
  }
  doStep3(resorce);
  if (error()) {
        return error;
  }
  doStep4(resorce);
  if (error()) {
        return error;
  }

  return error;
}


I think the former is much clearer. (Besides beeing faster if no exception
occurs.)
The case against ErrorCodes gets worse the farar away the functions who
catch the error is from the cause of the exceptional Situation.


I like to add that some of the points that Peter Ammon rises are no longer
valid (especially those regarding compiler support).

Regards 

Fabio









0
Reply f.fracassi (47) 4/24/2005 3:43:19 PM

In article <d4geqn$92v$02$1@news.t-online.com>, f.fracassi@gmx.net 
says...

> The main problems of exceptional situations is that they are well
> exceptional. You don't except them. Or put differently, you have to be
> constantly on the watch.

Ironically enough, the most common use of exceptions may be for i/o 
etc., where 'file not found' etc. are not at all exceptional.

It depends on the software, I should think.  For self-contained desktop 
software such as games or spreadsheets, i/o exceptions can usefully be 
handled, but if you run out of memory, for example, there's probably 
nothing you can do that is much better than stopping and saying you are 
out of memory.  Which the OS will do anyway.  Exceptions don't really 
add much to the defensive programmer's armoury.

(Saving the user's work is probably not on after a memory exception is 
thrown, so periodic autosave is the answer here.)

On the other hand, something that is supposed to stay up for months 
should have robust error handling, and in such cases exceptions could 
prove useful.

To put it another way, recovery from seriously unexpected events is 
going to be iffy at best, and effort might be best directed elsewhere 
(into preventing unexpected events) in cases where a rare program crash 
is not a disaster.

- Gerry Quinn

 
0
Reply gerryq (1321) 4/25/2005 8:51:03 AM

Gerry Quinn wrote:

> In article <d4geqn$92v$02$1@news.t-online.com>, f.fracassi@gmx.net
> says...
> 
>> The main problems of exceptional situations is that they are well
>> exceptional. You don't except them. Or put differently, you have to be
>> constantly on the watch.
> 
> Ironically enough, the most common use of exceptions may be for i/o
> etc., where 'file not found' etc. are not at all exceptional.
> 
Au contraire. C++ iostreams don't even throw exceptions in this case (unless
you tell them to.)

Exceptions are generaly a good Idea, where checking for exceptional
Conditions in advance is either computationally expensive, or subject to
race conditions.

> It depends on the software, I should think.  For self-contained desktop
> software such as games or spreadsheets, i/o exceptions can usefully be
> handled, but if you run out of memory, for example, there's probably
> nothing you can do that is much better than stopping and saying you are
> out of memory.  Which the OS will do anyway.  Exceptions don't really
> add much to the defensive programmer's armoury.
> 
> (Saving the user's work is probably not on after a memory exception is
> thrown, so periodic autosave is the answer here.)

Why not? Your assuming that all data is absolutly needed, and has to be
saved. Clean some suplimental Data structures like hashtables for fast
access, or simmilar, and save the relevant user data.

Quite often the Memory is not taken by the user Data, but by temporary
values needed to execute certain operations. Let's stay in the Spreadsheet
example: Imagine you want to add a realy huge and eye candy ladden Diagramm
created from the Data. Now you run out of memory. Do you realy want your
spreadsheet to crash? I'd rather have it say "Not enough memory to create
Diagramm". Then you can either kill that video transcoding Process thats
running in the background, or add a diagramm with less Eye Candy, that
hopefully takes less memory.

A very nifty trick to dynamically solve the time/space tradeoff is to try to
use an memory intesive algorithm, and in case it fails use another
algorithm, which takes less memory (but is probably slower than the other
one would have been.)

> 
> On the other hand, something that is supposed to stay up for months
> should have robust error handling, and in such cases exceptions could
> prove useful.
> 

And why shouldn't my spreadsheet or game fit into these category?

> To put it another way, recovery from seriously unexpected events is
> going to be iffy at best, and effort might be best directed elsewhere
> (into preventing unexpected events) in cases where a rare program crash
> is not a disaster.

The problem is that you can't. How can you prevent that a file you want to
read from isn't deleted in the exact moment you wanted to read from it, how
do you prevent that the file you read isn't corrupted, etc ...
You always have to make assumtions, but you should deal gratiously with the
situations where your assumptions break.

Fabio











0
Reply f.fracassi (47) 4/26/2005 8:53:47 AM

In article <d4kvoa$gla$01$1@news.t-online.com>, f.fracassi@gmx.net 
says...
> Gerry Quinn wrote:

> > Ironically enough, the most common use of exceptions may be for i/o
> > etc., where 'file not found' etc. are not at all exceptional.
> > 
> Au contraire. C++ iostreams don't even throw exceptions in this case (unless
> you tell them to.)

The popular MFC library throws an exception in such cases.  I doubt it 
is unique.

> Exceptions are generaly a good Idea, where checking for exceptional
> Conditions in advance is either computationally expensive, or subject to
> race conditions.

> > It depends on the software, I should think.  For self-contained desktop
> > software such as games or spreadsheets, i/o exceptions can usefully be
> > handled, but if you run out of memory, for example, there's probably
> > nothing you can do that is much better than stopping and saying you are
> > out of memory.  Which the OS will do anyway.  Exceptions don't really
> > add much to the defensive programmer's armoury.
> > 
> > (Saving the user's work is probably not on after a memory exception is
> > thrown, so periodic autosave is the answer here.)
> 
> Why not? Your assuming that all data is absolutly needed, and has to be
> saved. Clean some suplimental Data structures like hashtables for fast
> access, or simmilar, and save the relevant user data.

While you *can* do this, such code will require extensive testing - 
more testing than it is likely to get.  Okay, it depends on the 
particular program.  If the exception handling goes wrong, it may even 
overwrite good data, and the user will lose more work, not less.  

The best can sometimes be the enemy of the good. 

> > On the other hand, something that is supposed to stay up for months
> > should have robust error handling, and in such cases exceptions could
> > prove useful.

> And why shouldn't my spreadsheet or game fit into these category?

Because in many cases 100% stability will not be critical.
 
> > To put it another way, recovery from seriously unexpected events is
> > going to be iffy at best, and effort might be best directed elsewhere
> > (into preventing unexpected events) in cases where a rare program crash
> > is not a disaster.

> The problem is that you can't. How can you prevent that a file you want to
> read from isn't deleted in the exact moment you wanted to read from it, how
> do you prevent that the file you read isn't corrupted, etc ...
> You always have to make assumtions, but you should deal gratiously with the
> situations where your assumptions break.

Certainly that is true, but it is a counsel of perfection.  Where 
resources are finite, they must be allocated according to need.

And there is also the point that simply by the nature of things, code 
that deals with false assumptions is likely to be poorly tested and 
consequently is more likely to contain bugs anyway!

- Gerry Quinn
 





0
Reply gerryq (1321) 4/26/2005 9:23:36 AM

Gerry Quinn wrote:

> In article <d4kvoa$gla$01$1@news.t-online.com>, f.fracassi@gmx.net
> says...
>> Gerry Quinn wrote:
> 
>> > Ironically enough, the most common use of exceptions may be for i/o
>> > etc., where 'file not found' etc. are not at all exceptional.
>> > 
>> Au contraire. C++ iostreams don't even throw exceptions in this case
>> (unless you tell them to.)
> 
> The popular MFC library throws an exception in such cases.  I doubt it
> is unique.
> 

I never use platform dependend code, so I never used MFC.


>> > (Saving the user's work is probably not on after a memory exception is
>> > thrown, so periodic autosave is the answer here.)
>> 
>> Why not? Your assuming that all data is absolutly needed, and has to be
>> saved. Clean some suplimental Data structures like hashtables for fast
>> access, or simmilar, and save the relevant user data.
> 
> While you *can* do this, such code will require extensive testing -
> more testing than it is likely to get.  Okay, it depends on the
> particular program.  If the exception handling goes wrong, it may even
> overwrite good data, and the user will lose more work, not less.

Why? You don't have to overwrite the users last save. Save it as something
like .appname_emergency_save_<id> and ask the user if he wants to load it
the next time the app is started.

But if you programm with exception safety in mind the Data shouldn't be at
risk.

> The best can sometimes be the enemy of the good.

???


>> > To put it another way, recovery from seriously unexpected events is
>> > going to be iffy at best, and effort might be best directed elsewhere
>> > (into preventing unexpected events) in cases where a rare program crash
>> > is not a disaster.
> 
>> The problem is that you can't. How can you prevent that a file you want
>> to read from isn't deleted in the exact moment you wanted to read from
>> it, how do you prevent that the file you read isn't corrupted, etc ...
>> You always have to make assumtions, but you should deal gratiously with
>> the situations where your assumptions break.
> 
> Certainly that is true, but it is a counsel of perfection.  Where
> resources are finite, they must be allocated according to need.

I don't understand what you are saying here. Lets take out of memory again:
I assume that I have enough memory for my opperation, so I do it. If my
assumption was false I get an exception, and act apropiately.
The fact is that I couldn't do it another way, because of reentrancy issus.
I couldn't check beforehand if I have enough memory, because even if my test
succeeded another process could eat it right after the test, but before the
allocation.
 
> And there is also the point that simply by the nature of things, code
> that deals with false assumptions is likely to be poorly tested and
> consequently is more likely to contain bugs anyway!

This is not my point. You are arguing about bugs, I talk about exceptional
situations. A programm with bugs will break, with or without exceptions.
Exceptions help with dealing with exceptional situations not with bugs.
I wasn't talking about wrong assumptions but about reasonable expectations
which in this case aren't fullfilled.

As I said before: 
"Exceptions are generaly a good Idea, where checking for exceptional
Conditions in advance is either computationally expensive, or subject to
race conditions."

Fabio






0
Reply f.fracassi (47) 4/26/2005 9:57:16 AM

Serge Skorokhodov (216716244) wrote:
> Hi,
> 
> <skip>
> 
>>4) C++ compilers do not consistently implement exceptions.
>>For example, last I checked, Visual C++ will return NULL
>>instead of throwing a bad_alloc exception (as required by the
>>standard) if new fails.  This makes exceptions more difficult
>>to include in portable code.
> 
> 
> I've tested the following snippet with vc.net 2003 right after
> read you post:
> 
> #include <iostream>
> #include <limits>
> #include <stdexcept>
> 
> using namespace std;
> 
> void main()
> {
> 	size_t how_many	=	numeric_limits<size_t>::max();
> 	try
> 	{
> 		double* pdbl	=	new double[how_many-1];
> 		if ( !pdbl )
>                       throw logic_error("new returned null!");
> 		delete[] pdbl;
> 	}
> 	catch ( const logic_error& le )
> 	{
> 		cout << le.what();
> 	}
> 	catch ( const exception& e )
> 	{
> 	    cout << e.what();
> 	}
> 	catch ( ... )
> 	{
> 		cout << "strange shit happend!";
> 	}
> }
> 
> bad allocation was the output so new throws std::bad_alloc now.
> 
> <skip>

Thanks, that's good to hear.

-Peter

-- 
Pull out a splinter to reply.
0
Reply gershwin (187) 4/27/2005 6:17:00 AM

Fabio Fracassi wrote:
[...]
> 
> There was a fairly long and heated Thead on comp.lang.c++.moderated recently
> about the pro and cons of exceptions. Try to find it in the Archives, if
> you are interested in it.
> 
> Exceptions have a few points to be aware of, and programming in an exception
> save way is not trivial (but not unmasterably difficult).
> It takes a bit to getting used to writing an exception save code, but the
> effort is well worth it, since these techniques increase your overall code
> quality.
> BUT: The same problems apply to other error catching mecanisms as well.
> The uncomfortable truth is, writing programms that deal well with
> exceptional situations is hard.
> 
> The question to ask is not should I use exceptions, but what do I have to do
> if I don't use them?
> 
> The main problems of exceptional situations is that they are well
> exceptional. You don't except them. Or put differently, you have to be
> constantly on the watch.

Well, no, not necessarily.

There's a dichotomy between what I've heard colorfully described as the 
"banker" and the "moon rover" approach.

If you're writing a banking program, you want any error to be caught 
immediately, and if it's not handled, to halt immediately, lest the 
error propogate further and silently cause mistakes in financial data. 
This is the philosophy where exceptions live.

But if you're writing a (remote) moon rover program, you want the moon 
rover to keep going as best it can, no matter what.  The proper thing to 
do if you get an unexpected error is to cross your fingers and ignore 
it.  This is where return values live.

Neither approach is a priori better, of course; it depends on what you 
want to write.

[...]

>(Besides beeing faster if no exception
> occurs.)
> The case against ErrorCodes gets worse the farar away the functions who
> catch the error is from the cause of the exceptional Situation.
> 
> 
> I like to add that some of the points that Peter Ammon rises are no longer
> valid (especially those regarding compiler support).
> 

I'm very happy to be wrong with respect to compiler support for exceptions!

-Peter

-- 
Pull out a splinter to reply.
0
Reply gershwin (187) 4/27/2005 6:43:00 AM

In article <As2dnVp8haTqqfLfRVn-rg@comcast.com>, 
gershwin@splintermac.com says...
> Fabio Fracassi wrote:

> If you're writing a banking program, you want any error to be caught 
> immediately, and if it's not handled, to halt immediately, lest the 
> error propogate further and silently cause mistakes in financial data. 
> This is the philosophy where exceptions live.
> 
> But if you're writing a (remote) moon rover program, you want the moon 
> rover to keep going as best it can, no matter what.  The proper thing to 
> do if you get an unexpected error is to cross your fingers and ignore 
> it.  This is where return values live.
> 
> Neither approach is a priori better, of course; it depends on what you 
> want to write.

While I agree with the banker / moon rover metaphor for error checking, 
I'm not sure the difference between exceptions and return values is 
key.  If you want, you can handle an exception, or you can quit on a 
bad return value.  Or vice versa.

- Gerry Quinn
0
Reply gerryq (1321) 4/27/2005 8:11:02 AM

In article <d4l3f8$tpr$05$1@news.t-online.com>, f.fracassi@gmx.net 
says...
> Gerry Quinn wrote:

> > While you *can* do this, such code will require extensive testing -
> > more testing than it is likely to get.  Okay, it depends on the
> > particular program.  If the exception handling goes wrong, it may even
> > overwrite good data, and the user will lose more work, not less.

> Why? You don't have to overwrite the users last save. Save it as something
> like .appname_emergency_save_<id> and ask the user if he wants to load it
> the next time the app is started.

You see, already you have to do messy extra things that won't be 
properly tested.

> > The best can sometimes be the enemy of the good.
> 
> ???

It's a proverb (maybe a quotation).  It means that by trying for 
perfection, you may not achieve as much as by settling for something 
more achievable.  Like a sculptor who smashes up all his works because 
none of them achieve his ideal.

> > Certainly that is true, but it is a counsel of perfection.  Where
> > resources are finite, they must be allocated according to need.
> 
> I don't understand what you are saying here. Lets take out of memory again:
> I assume that I have enough memory for my opperation, so I do it. If my
> assumption was false I get an exception, and act apropiately.
> The fact is that I couldn't do it another way, because of reentrancy issus.
> I couldn't check beforehand if I have enough memory, because even if my test
> succeeded another process could eat it right after the test, but before the
> allocation.

You are doing extra coding, that may not work, for something that 
should rarely happen.  Depending on the application, that may not be 
cost-effective.

> > And there is also the point that simply by the nature of things, code
> > that deals with false assumptions is likely to be poorly tested and
> > consequently is more likely to contain bugs anyway!
> 
> This is not my point. You are arguing about bugs, I talk about exceptional
> situations. A programm with bugs will break, with or without exceptions.
> Exceptions help with dealing with exceptional situations not with bugs.
> I wasn't talking about wrong assumptions but about reasonable expectations
> which in this case aren't fullfilled.
> 
> As I said before: 
> "Exceptions are generaly a good Idea, where checking for exceptional
> Conditions in advance is either computationally expensive, or subject to
> race conditions."

When you talk about race conditions, you are to some extent by 
implication talking about programs or at least threads that interact.  
Under such conditions it does probably become more important that each 
one stay up, and it may be that exceptions are typically of more use.

However, with a monolithic desktop program where failure is not 
critical, I suspect that extensive efforts to deal with the unexpected 
may often be misdirected.

- Gerry Quinn


0
Reply gerryq (1321) 4/27/2005 8:18:43 AM

Gerry Quinn wrote:

> In article <d4l3f8$tpr$05$1@news.t-online.com>, f.fracassi@gmx.net
> says...
>> Gerry Quinn wrote:

>> Why? You don't have to overwrite the users last save. Save it as
>> something like .appname_emergency_save_<id> and ask the user if he wants
>> to load it the next time the app is started.

> You see, already you have to do messy extra things that won't be
> properly tested.
> 

Not really, since most of the code (like load and save) is already done and
heavily tested. The newly written code should be some 5 - 10 lines, of
pretty trivial (i.e. safe) code.
Most Editors I know have such a feature, (and IIRC MS Office apps do too.)

Besides, if this functionaltiy breaks in rare cases, your still not worse of
than with the app simply crashing.


>> As I said before:
>> "Exceptions are generaly a good Idea, where checking for exceptional
>> Conditions in advance is either computationally expensive, or subject to
>> race conditions."
> 
> When you talk about race conditions, you are to some extent by
> implication talking about programs or at least threads that interact.
> Under such conditions it does probably become more important that each
> one stay up, and it may be that exceptions are typically of more use.
> 
No we don't. With regard to memory or filesystem you are subject to race
conditions even in Single-threaded Apps.
There is always a possibility that a user deletes a file that is currently
used, or fills disk space or memory. 

> However, with a monolithic desktop program where failure is not
> critical, 

Well I regard any application that crashes as buggy. If my browser crashes
because of a maleformed webpage, or my editor crashes because I deleted the
file I was editing, I will be anoyed. Such things simply don't need to
happen.

> I suspect that extensive efforts to deal with the unexpected 
> may often be misdirected.

It may happen, but I guess it is rather seldom. Good Software should stay
alive even if unusual situations occur. 


Fabio






0
Reply f.fracassi (47) 4/27/2005 8:50:37 AM

22 Replies
26 Views

(page loaded in 0.351 seconds)

Similiar Articles:


















7/18/2012 9:42:13 AM


Reply: