Topic: Exception specifier in function declaration


Author: Greg Colvin <spam@me.not>
Date: 1998/10/25
Raw View


J. Kanze <kanze@gabi-soft.fr> wrote in article
<m3ogr69uno.fsf@gabi-soft.fr>...
> I think I agree, but I've seen very little published work in this
> direction.  Most of the classical reasoning about program correctness is
> based on control flow, and exceptions wreck havoc with it.  (I'm happy
> to see that David Abrahams has turned up something, even if it is by a
> proponent of a certain program style, and not one of your major
> theorists.)

I'm just now reading an OOPSLA '98 article called "Reasoning about
Java Classes" which shows that exceptions are not a problem for
automated theorem proving in a higher order logic.  Check out:

   http://www.cs.kun.nl/~bart/papers.html

It looks to be very solid work, but I'm no mathematician.

Greg Colvin

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]




[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: AllanW@my-dejanews.com
Date: 1998/10/26
Raw View
> In article <6v2vks$l1l$1@nnrp1.dejanews.com>, AllanW@my-dejanews.com
> writes
> >WHY does this scare you? Would you feel more secure if they were
> >forced to use Ada? Assembly language? Java? COBOL? BASIC?

In article <QYnR6GAMIrF2Ew65@robinton.demon.co.uk>,
  Francis Glassborow <francisG@robinton.demon.co.uk> wrote:
> Actually (and I warn you that you will not like this answer) C.  Not
> just C by itself but coupled with an appropriate set of coding standards
> enforced by a proper set of development tools.
>
> I  certainly would not become complacent but at least developers would
> have a fighting chance (Oh I too can spin lists of problems, such as who
> proves the hardware etc.)

You're missing the point. Given an equivalent set of coding standards,
and an equivalent set of development tools (which may be hard to find
for C++ for a few months yet), C++ (or Java or BASIC etc) is no more or
less safe than C. There's nothing about the C language that
automatically makes it a safer language.

Go ahead and spin your list, but be certain that the list contains
issues that are relevant for C++ developers, and *not* for C
developers. And don't cite bad code, either; we both know that not
every line of C code ever written is textbook perfect. Citing bad
C++ code only proves that the problem has not gone away, which is
certainly not controversial.

Compare well-written C to well-written <insert language here>, and
you'll find that they have similar properties WRT safety.

> Before responding you might try reading Safer C by Les Hatton.

Is there some point there that I've overlooked?





I'd like to direct the reader's attention to the subject line of
this post. The question wasn't about "language wars" but about
"exception specifiers." Certainly they were designed to help make
programs more safe. Did they achieve that goal?

I think that they did not. As they exist right now, these
throw-specs can redirect a throw to unexpected(), but they serve
no other purpose.

But I think it can be fixed, perhaps fairly easily. We need two
things:
    (1) Consider calling unexpected() as bad as calling abort().
        That is, recognize that reaching this point is a
        catastrophe, representing a fatal mistake in the program.
        Write unexpected() with this understanding in mind.
    (2) Issue compile diagnostics for code that does not seem
        to follow that philosophy.

That second point probably needs elaboration.

    struct A{};
    struct B{};
    struct C{};
    struct D{};
    struct E{};
    struct F{};
    struct G{};
    int e(); // Can throw anything
    int d() throw(A,B,C,D,E,F,G); // Can throw these specific types

    int c() throw(A,B,C,D,E) {

        e(); // Generate a warning
            // "Unguarded call to function with greater throw-spec"

        d(); // Generates the same warning

        throw G(); // Warning
            // "Throw specifies a type not in the throw-spec"

        try {
            d(); // Causes the warning below
            throw G(); // OK because there's a matching catch() here
        } catch (A a) {
            // ...
        } catch (C c) {
            // ...
        } catch (E e) {
            // ...
        } catch (G g) {
            // ...
        }
        // Warning: nothing catches F which can be thrown by d()

        try {
            d(); // OK because the catch(...) catches everything
        } catch(...) {
        }
        // No warning here
    }

Some criticism of this idea can be found in earlier posts. For
instance:

    struct Domain_Error {};

    // Not to be confused with sqrt()
    double square_root(double value) throw(Domain_Error) {
        if (value > 1.0)
        {
            // Establish range of guesses
            double lo = 1.0;
            double hi = value;
            while (true) {

                // Make a guess. Other formulae are possible.
                double guess = (lo + hi) / 2.0;

                // Check for epsilon; if we're trying to repeat a number,
                // then we're as far as precision can take us
                if (guess>=lo || guess<=hi) return guess;

                // Is the guess correct? If not, adjust range for next pass
                double v = guess * guess;
                if      (v<value) lo=guess;
                else if (v>value) hi=guess;
                else return guess;
            }
        }
        if (value < 1.0)
        {
            // Check for invalid operand
            if (value < 0.0)
                throw Domain_Error();

            // Establish range of guesses
            double lo = value;
            double hi = 1.0;
            while (true) {

                // Make a guess. Other formulae are possible.
                double guess = (lo + hi) / 2.0;

                // Check for epsilon; if we're trying to repeat a number,
                // then we're as far as precision can take us
                if (guess>=lo || guess<=hi) return guess;

                // Is the guess correct? If not, adjust range for next pass
                double v = guess * guess;
                // Counterintuitive: n squared is less than n, for 0<n<1
                // So high products mean that the guess was too low...
                if      (v<value) hi=guess;
                else if (v>value) lo=guess;
                else return guess;
            }
        }
        // value == 1.0
        return 1.0;
    }

    // Here's a function that uses square_root:
    void hash(double value) {
        if (value<1.0)
            return value;
        if (value<1000.0)
            return square_root(value); // Oops! * * * * * * * *
        return value-1000.0;
    }

hash() calls square_root if the value is between 1.0 and 1000.0.
We know that square_root() will not throw a Domain_Error with this
argument, but the compiler cannot be that clever. We are forced
to deal with the case even though the probability is 0.

But I say this is no different than this case:
    if (c=d) { /* ... */ }
The above is legal C; it copies the value from d into c, and then
it executes the /*...*/ if that value was non-zero. But many
compilers will issue a warning:
     warning C4706: assignment within conditional expression
because you *PROBABLY* meant:
    if (c==d) { /* ... */ }
which has a very different meaning. If we really did want the
first version, we write
    if (0!=(c=d)) { /* ... */ }
which has the same meaning, and rely on the compiler to optimize
away any other differences.

The same would apply to the exception-spec violation above. We
simply code:
            try {
                return square_root(value); // Oops! * * * * * * * *
            } catch (Domain_Error) {}
Hopefully the compiler can optimize away the null catch. I don't
know of any compiler that would optimize this away today, but I'm
sure there will be some soon.

--
AllanW@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/10/26
Raw View
In article <70nocu$6f7$1@nnrp1.dejanews.com>, AllanW@my-dejanews.com
writes
>Is there some point there that I've overlooked?
>
I think if you had read 'Safer C' you would know there was.  The
complexity of C++ as well as the large number of defects in its standard
(that is not a criticism as such -- I have been involved in developing
that standard) means that there are no tools that are close to being
comporable to those that are available for enforcing suitable guidelines
for mission critical (or as Les Hatton cals them 'High Integerity')
systems.  Part of this is language maturity (the flaws and dangerous
areas of C are well known to those that need to know -- well some of
them) part is the level of complexity.

Note that I like C++ but that does not completely blind me to its
shortcomings (though there may be a tint of rose in my spectacles)
however I also continue to believe that C has its place and part of that
is in coding mission critical systems.


Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: "Greg Colvin" <spam@me.not>
Date: 1998/10/26
Raw View
> |>  However, exception safety in C++ and similar languages does
> |>  not depend on analyzing all possible program flows, but rather
> |>  on designing code such that no matter what control path is
> |>  taken the invariants of object state are maintained.  In my
> |>  experience exception specifications beyond throw() are not of
> |>  much help in such design.
>
> I think I agree, but I've seen very little published work in this
> direction.  Most of the classical reasoning about program correctness is
> based on control flow, and exceptions wreck havoc with it.  (I'm happy
> to see that David Abrahams has turned up something, even if it is by a
> proponent of a certain program style, and not one of your major
> theorists.)

I'm reading an interesting paper on static analysis of C language
called "Detecting Memory Errors via Static Pointer Analysis" from the
Proceedings of the ACM SIGPLAN/SIGSOFT Workshop on Program Analysis
for Software Tools and Engineering.  Check out:

   http://www.math.tau.ac.il/~nurr/

The paper introduces the idea of "cleaness conditions" and states that:

  "An important property of all cleaness conditions is that they are
   absolute, namely, they must hold for all programs, as opposed to
   the notion of program correctness which is relative to a given
   specification."

As much as possible, I think software should be designed to be safe
based on such "cleaness conditions".

I'm  also reading an OOPSLA '98 article called "Reasoning about
Java Classes" which shows that exceptions are not a problem for
automated theorem proving in a higher order logic.  Check out:

   http://www.cs.kun.nl/~bart/papers.html

It looks to be very solid work, but I'm no mathematician.

Greg Colvin

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: William Clodius <wclodius@lanl.gov>
Date: 1998/10/26
Raw View
[Moderator's note: this thread has drifted off-topic.
 Followups regarding the history of programming languages
 would be best directed to comp.lang.misc. -mod(fjh).]

AllanW@my-dejanews.com wrote:
> <snip>
> I was under the impression that the first two HLL's were Fortran and
> COBOL.
> <snip>

Fortran was the first widely used HLL and the oldest still with
significant useage, but it was not the first HLL. Earlier HLL's were
typically interpreted, non-portable, and used only at one site. The
first description of an HLL appeared in 1945, Plankalkul by Zuse, but
may never have been implemented. The Language List

http://cuiwww.unige.ch:80/langlist

gives several other languages before May 1957 when Fortran was
commercially released after over a year of external beta testing.
Depending on whether you count APT as a higher level language (its used
to program machine tools) Lisp is the second or third oldest widely used
language, I believe the Lisp 1 manual was published in early 1958, Lisp
1.5 in 1959. Cobal was first defined in Apr. 1960.

--

William B. Clodius  Phone: (505)-665-9370
Los Alamos Nat. Lab., NIS-2     FAX: (505)-667-3815
PO Box 1663, MS-C323     Group office: (505)-667-5776
Los Alamos, NM 87545            Email: wclodius@lanl.gov


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: abrahams@spam.motu.com (David Abrahams)
Date: 1998/10/27
Raw View
On 26 Oct 98 05:56:29 GMT, AllanW@my-dejanews.com wrote:

>The question wasn't about "language wars" but about
>"exception specifiers." Certainly they were designed to help make
>programs more safe. Did they achieve that goal?
>
>I think that they did not. As they exist right now, these
>throw-specs can redirect a throw to unexpected(), but they serve
>no other purpose.
>
>But I think it can be fixed, perhaps fairly easily. We need two
>things:
>    (1) Consider calling unexpected() as bad as calling abort().
>        That is, recognize that reaching this point is a
>        catastrophe, representing a fatal mistake in the program.
>        Write unexpected() with this understanding in mind.
>    (2) Issue compile diagnostics for code that does not seem
>        to follow that philosophy.

I have two questions:

1. How would your proposal make programs more safe (and safe from
what, I might add)?

2. How would you deal with the maintainance problems associated with
broadening a function's exception-specificiation?

-Dave

P.S. For the record, I note that nobody I spoke to ever seemed want
automated restriction of the range of error conditions that could be
reported by a function which returned error codes...
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "James Russell Kuyper Jr." <kuyper@wizard.net>
Date: 1998/10/20
Raw View
J. Kanze wrote:

> AllanW@my-dejanews.com writes:
....
> |>  > It would be nice to think that the language chosen allowed
efficient
> |>  > reasoning about program logic.
> |>
> |>  Naturally. And they all do, except that each one has at least one
> |>  strength not seen in other languages (if this were not so, there
> |>  would be no reason to invent a new language).

> I wonder if you've ever written (or read) Fortran IV :-).

I did, in 1979. It was great improvement over Fortran I, which was the
only version I'd previously been exposed to. What was wrong with it
(other than that it wasn't C)?

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/10/21
Raw View
In article <6v2vks$l1l$1@nnrp1.dejanews.com>, AllanW@my-dejanews.com
writes
>WHY does this scare you? Would you feel more secure if they were
>forced to use Ada? Assembly language? Java? COBOL? BASIC?

Actually (and I warn you that you will not like this answer) C.  Not
just C by itself but coupled with an appropriate set of coding standards
enforced by a proper set of development tools.

I  certainly would not become complacent but at least developers would
have a fighting chance (Oh I too can spin lists of problems, such as who
proves the hardware etc.)

Before responding you might try reading Safer C by Les Hatton.



Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/21
Raw View
Greg Colvin <spam@me.not> writes:

|>  On 6 Oct 1998 09:06:47 -0400, kanze@gabi-soft.fr (J. Kanze) wrote:
|>  >Today, at any rate; I'm
|>  >more and more convinced that there is a way of rigorously reasoning
|>  >about program correction based on object state, rather than program
|>  >flow, although I've yet to seen anyone explain it.  (And of course,
|>  >reasoning about program correction based on object state pretty much
|>  >eliminates the objections to exceptions.)
|>
|>  As understand it, one can prove a program "correct" only with
|>  respect to a specification, and only by reasoning about program
|>  flow.  However:
|>
|>    "Just because a program is 'proven correct' ... you cannot be
|>     sure it will do what you intend."
|>
|>       -- Brian Cantwell Smith, "The Limits of Correctness,"
|>       Proceedings of the Symposium on Unintentional Nuclear War,
|>       Fifth Congress of the International Physicians for the
|>       Prevention of Nuclear War, 1985
|>
|>  The problem with correctness proofs is that they are only as
|>  good as the specification, and say nothing about how much
|>  damage a program might do if the specification turns out
|>  to be wrong.  So I say that if safety requires correctness
|>  no language is safe enough.

Which was more or less my point.  Either that no language is safe
enough, or that all are.  Safety is an issue that transcends languages.

On the other hand, while I totally agree concerning the limits of
reasoning about programs (the program that failed in the Ariana 5 was
totally correct with regards to the specifications to which it was
programmed), that doesn't mean that you don't want to verify the program
either.  And by verification, I mean both rigorous reasoning about the
program's correction (in stringent code reviews), and extensive
testing.  When human lives (or billions of dollars) are at stake, you
don't want to ignore anything which might avoid an error.

|>  However, exception safety in C++ and similar languages does
|>  not depend on analyzing all possible program flows, but rather
|>  on designing code such that no matter what control path is
|>  taken the invariants of object state are maintained.  In my
|>  experience exception specifications beyond throw() are not of
|>  much help in such design.

I think I agree, but I've seen very little published work in this
direction.  Most of the classical reasoning about program correctness is
based on control flow, and exceptions wreck havoc with it.  (I'm happy
to see that David Abrahams has turned up something, even if it is by a
proponent of a certain program style, and not one of your major
theorists.)

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orientie objet --
              -- Beratung in objektorientierter Datenverarbeitung
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: AllanW@my-dejanews.com
Date: 1998/10/22
Raw View

> |>  In article <m3hfxkqyho.fsf@gabi-soft.fr>,
> |>    kanze@gabi-soft.fr (J. Kanze) wrote:
> |>  > It would be nice to think that the language chosen allowed efficient
> |>  > reasoning about program logic.

> AllanW@my-dejanews.com writes:
> |>  Naturally. And they all do, except that each one has at least one
> |>  strength not seen in other languages (if this were not so, there
> |>  would be no reason to invent a new language).

In article <m3lnmc5ygr.fsf@gabi-soft.fr>,
  kanze@gabi-soft.fr (J. Kanze) wrote:
> I wonder if you've ever written (or read) Fortran IV :-).

Yes, although it was many years ago and I've probably forgotten
more than I remember.

[[ One thing that I liked about Fortran was the if-statement's
ability to have a single test do three things (based on negative,
zero, positive), rather than the more common two things (true,
false). One had to use a construct similar to "goto" for this to
work, however. --What do I win? ]]

I expect that program authors and maintainers are professionals. Thus,
they will be well-versed in the language, including all (or at least a
vast majority) of it's nuances. To a multi-lingual programmer,
    x = 5; // Set variable x to value 5
or
    C      Set variable x to value 5
           x = 5
or
         * Set variable x to value 5
           x = 5 .
or
           LET X = 5 : REM Set variable x to value 5
or
    [1] x=5 ' Set variable x to value 5
are all pretty much equivalent. Notice that the comment in each of
these cases is useless in the context I just quoted -- thus the
restriction (which these comment violate) that a comment should
explain WHY the program does something, rather than WHAT it does.

Given that context, a programmer fluent in language X should be able
to read well-written X code, understand it's point, and even
"efficient[ly] reason about [it's] program logic". If this is not
possible, then by my definition either the X program or the X
programmer is not at a professional level (in language X).

Naturally, we must make allowances for real-world concerns such as
"learning curve" and "paradigm shift," but these should be the
exception rather than the rule -- and there are ways of minimizing
the impact of these exceptions.

> In fact, cleanly written C++ isn't too bad when it comes to reasoning
> about program logic.  The only real complaint is that it is so easy to
> slip, and not be as clean as one would like.  (Note that this is a
> relative criteria.  It is possible to write illogical programs in any
> language, despite Bertrand Meyer's claims for Eiffel.  And one of the
> most cleanly written programs I ever saw was written in Fortran IV.
> Never the less, I think it safe to say that different languages
> "encourage" clean writing more than others, and that C++ is,
> regretfully, one that encourages it less than many others.)

I agree with all of this except the last. After all, this "encouragement"
can only go so far. I think C++ is pretty good at going up to that line
but not over it.

By contrast, consider an allegedly cross-platform 4GL called "CSP".
Among other Draconian measures, this language has no "goto", and it
enforces a rule that all subroutines will have either 0 or 1 I/O
statements. This is apparently a failed attempt to prohibit spaghetti
code. The result is that most (at least 3/4 of) all programs I saw had
at least a few subroutines which were nothing at all except for a single
I/O statement, which could be called from the subroutine that really
needed to do the I/O in a more logical place. Yeech. You could argue
that these programmers worked against the language instead of with it,
and I would agree, but still ... Yeech.

This experience taught me to avoid languages where the language
designers tried to ban bad code. The C++ language does not attempt
to force it's programmers to be good little programmers. But it does
provide all of the tools needed to *allow* well-written C++ code.
To me, that is exactly the line that a good programming language
should take.

> |>  > Of course, this can be achieved as well
> |>  > by eliminating the particular constructs which create the difficulties;
> |>  > a great deal of critical programming is done in Ada, for example, but it
> |>  > is generally a project rule to forbid the use of exceptions.
> |>  >
> |>  > Other than that, the simpler the language, the better, as it increases
> |>  > the chances that the compiler writer got it right.  (Given that Ada is
> |>  > generally the language of choice, however, one wonders.)  On the other
> |>  > hand, too much simplicity (i.e. assembler) is just pushing the problem
> |>  > into the hands of the programmer.  Of course, simplicity or
> |>  > orthogonality is also increases the chances that the programmer
> |>  > understands the language well enough so that his code does what he
> |>  > thinks it does.
> |>
> |>  Well, of the six languages mentioned at the top of this note, you have
> |>  dismissed four. The sentence in parens above seems to cast dispersions
> |>  on Ada as well, leaving COBOL unscathed, winner by default. Clearly, as
> |>  one of the first two "high-level" languages, it can claim the title of
> |>  Stable.
>
> Have you seen the latest version of the COBOL standard:->?  (Also, it
> isn't one of the first two "high-level" languages, as at least Fortran
> and Lisp predate it.)

I was under the impression that the first two HLL's were Fortran and
COBOL.

> Actually, if I didn't mention COBOL, it was because it seemed self
> evident to me that it doesn't even come close to meeting the reasoning
> about program logic criteria.

One of COBOL's strengths is that (well-written) COBOL often reads
similar to English. My non-technical manager can't write COBOL, but
he can read it. Doesn't this at least come close to your criterion?

> |>  Or can it? COBOL has been changing every few years, just as Ada and C
> |>  and now C++ have been changing. Naturally, one goal is backwards
> |>  compatibility; like C, they have been mostly but not completely
> |>  successful in that goal.
> |>
> |>  In any case, I doubt you will convince me that a 20,000-line COBOL
> |>  program is better for "safety critical systems" than a 6,000-line
> |>  C++ programmer, given similar working conditions (i.e. experience of
> |>  coders and testers, detailed specs, test scripts, etc.).
>
> I wouldn't even try.  I might, however, consider that a 10000 line Ada
> program would probably be superior than a 6000 line C++ one.

Why?

> However, your "conditions" are the real key.  Writing safety critical
> applications is a specialty in its own right, and more important than
> the language is getting people qualified in this specialty.  Just
> knowing C++ (or Ada, or whatever) isn't enough.  And most of the
> literature concerning C++ is NOT critical system oriented.

This is more or less my point. The computer language is part of a
larger context, which employs many tools. Safety-critical
applications are neither more nor less dangerous because of the
choice of computer language.

> |>  > Globally, I wouldn't be afraid if I learned they were using C++, per se.
> |>  > I would be afraid if I found out they were using all of the most recent
> |>  > features of the language -- for really safety critical systems, I'd
> |>  > probably limit myself to the subset supported by CFront 2.1, although I
> |>  > can imagine that allowing very simple templates (e.g. those that use no
> |>  > other tempates in their implementation) might be acceptable.
> |>
> |>  Hmmm. A "naive" policy would be to use language features whenever they
> |>  help to solve a problem, and to avoid using them at all other times
> |>  (i.e. avoid using "pointer to member" for reasons such as "show the
> |>  other programmers who's the real hot-shot).
> |>
> |>  You propose a different policy -- one that forbids "new" features --
> |>  presumably spelled out somewhere, and applied to all programmers on
> |>  the project. On the surface, this sounds extremely reasonable. But
> |>  recognize that all of the CFront features were once brand-spankin'-new
> |>  features too, so there MUST be some way that a new "unsafe" feature
> |>  becomes an old "safe" feature in your mind. The obvious, but least
> |>  logical method, would be the passage of time.
>
> Use.  Not all systems are safety critical.  I prefer to let the new
> features acquire the experience necessary to become old features in less
> safety critical systems, that's all.

Yes, exactly. So, in order to eventually use them in safety-critical
systems, you MUST use them in some other programs much sooner.

> This applies to all languages, not just C++.  I know of at least one
> very large critical application which is moving from Ada (83) to C++.
> Because they want to use an OO paradigm, and the OO support
> (inheritance) in C++ is more "stable" (older) than that in Ada '95.
> They are still very much in the early stages, but I imagine that they
> will eschew many of the more modern features, and probably the entire
> STL, on the grounds of their being too new and unstable.

An interesting philosophy. Certainly they did a cost-benefits study
before jumping to this conclusion? Perhaps they compared the added
productivity to the estimated testing that would be required?

> |>  May I suggest an alternative? Write a test program that uses new features.
> |>  Write a LOT of test programs, using ALL the new feature in EVERY
> |>  conceivable way. For each test program, write down the expected results
> |>  before you execute the program. Now compile and execute the test
> |>  programs on as wide of a variety of "compliant" compilers as you can.
> |>  Examine the actual results and compare them to the expected results.
>
> Do you have any idea how much work it would be to do that.  Perenial
> (and others) have such suites available.  I know of no compiler which
> passes all of the tests in the Perenial test suite.

The "less safety critical systems" are at least some of your test
programs, provided that they are written in a way that allows you to
detect this type of error.

As for the test suite not passing on any compiler, that's exactly the
point. (What good is a test suite that always succeeds?) Features that
don't run reliably on all of your important targets should be avoided
for now (but try again in 6 months or a year). The rest can be used
right away, even in your "safety critical" systems.

> |>  Does "goto" make a program unstable?
>
> Anything that violates the single entrance/single exit principle makes
> reasoning about program correctness more difficult.

Does goto ever do that? If so, does it always do that? Very powerful
statement, this goto.

-----------== Posted via Deja News, The Discussion Network ==----------
AllanW@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/22
Raw View
Christopher Eltschka <celtschk@physik.tu-muenchen.de> writes:

|>  Andrew Bell wrote:
|>
|>  [...]
|>
|>  > To do static analysis of exceptions, the compiler doesn't need a spec
|>  > on the template, it can just look at the template definition, which
|>  > calls operator==() on two Foos.  So if the Foo constructor can't
|>  > throw, and that operator==() can't throw, we're in fine shape.
|>
|>  However, as soon as the compilers implement the export keyword,
|>  there will be templates which cannot be effectively checked at
|>  compile time. Of course, we could pass the information to the linker
|>  and check at link time.

Not at all, since the standard explicitly allows an implementation to
require the export'ed templates to be compiled before use.  Thus, for
example, an implementation which simply copied the exported template
code verbatim into the object file, required the object file to be
accessible at compile time, and otherwise worked exactly as it does
today, would be fully compliant.

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orient   e objet --
              -- Beratung in objektorientierter Datenverarbeitung

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]




[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/22
Raw View
"James Russell Kuyper Jr." <kuyper@wizard.net> writes:

|>  J. Kanze wrote:
|>
|>  > AllanW@my-dejanews.com writes:
|>  ....
|>  > |>  > It would be nice to think that the language chosen allowed
|>  efficient
|>  > |>  > reasoning about program logic.
|>  > |>
|>  > |>  Naturally. And they all do, except that each one has at least one
|>  > |>  strength not seen in other languages (if this were not so, there
|>  > |>  would be no reason to invent a new language).
|>
|>  > I wonder if you've ever written (or read) Fortran IV :-).
|>
|>  I did, in 1979. It was great improvement over Fortran I, which was the
|>  only version I'd previously been exposed to. What was wrong with it
|>  (other than that it wasn't C)?

For its day, nothing.  (Back then, the only real alternative was
assembler.)  Still, no user defined data types (not even structures),
and no flow control except a very strange FOR, for starters.  Not to
mention a 6 character max. for symbol names (and implicit declaration of
type depending on the first letter of the symbol).

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orientie objet --
              -- Beratung in objektorientierter Datenverarbeitung
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "Greg Colvin" <spam@me.not>
Date: 1998/10/23
Raw View
J. Kanze <kanze@gabi-soft.fr> wrote in article
<m3ogr69uno.fsf@gabi-soft.fr>...
> Greg Colvin <spam@me.not> writes:
> ...
> |>  However, exception safety in C++ and similar languages does
> |>  not depend on analyzing all possible program flows, but rather
> |>  on designing code such that no matter what control path is
> |>  taken the invariants of object state are maintained. ...
>
> I think I agree, but I've seen very little published work in this
> direction. ...

I'm reading an interesting paper on static analysis of C language
called "Detecting Memory Errors via Static Pointer Analysis" from the
Proceedings of the ACM SIGPLAN/SIGSOFT Workshop on Program Analysis
for Software Tools and Engineering.  Check out:

   http://www.math.tau.ac.il/~nurr/

The paper introduces the idea of "cleaness conditions" and states that:

  "An important property of all cleaness conditions is that they are
   absolute, namely, they must hold for all programs, as opposed to
   the notion of program correctness which is relative to a given
   specification."

As much as possible, I think software should be designed to be safe
based on such "cleaness conditions".

Greg Colvin

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Jerry Leichter <leichter@smarts.com>
Date: 1998/10/23
Raw View
| [C as a more secure language than C++] Before responding you might try

| reading Safer C by Les Hatton.

I'll second that - especially the recommendation of Safer C.

C++ certainly does have its advantages on this front, mainly in stronger
type checking.  And, if used appropriate, private members are very
powerful.  But you *can* choose to program in C in a type-safe way, and
if you do so and have a decent compiler, you can get it to do almost as
thorough a job of type checking.  (You'll want a compiler that you can
set to check for some things - like missing prototypes - that are legal
in C.)

There are also a variety of tools to help you write more secure C.  An
example - certainly not the only one - is lcLint, a C binding for the
Larch specification language (see http://www.sds.lcs.mit.edu/spd/).
On thing lcLint can give you is the logical equivalent of "private" in
C.

There are few C++ tools of this sort because C++ is so much more
complex.  An "lc++Lint" for C++ would probably be an order of magnitude
or two more difficult to build than lcLint - there's so much more pre-
defined semantics in C++, and it's so much more complex.  (Of course,
you'd need a parser for C++ to start with - a much more difficult
undertaking than one for C.  Eventually, such things will be available
"off the shelf", but it'll be years.  They are sorely needed.)

It's not "object orientation" that's the issue - there's a Larch
interface and checker for Modula-3, too.

BTW, a sad sign of just how much the market really seems to care about
safe programming:  Safer C is out of print.  (I believe it was published
in 1995, and was already out of print 6 months ago.)

       -- Jerry

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Greg Colvin <spam@me.not>
Date: 1998/10/19
Raw View

On 6 Oct 1998 09:06:47 -0400, kanze@gabi-soft.fr (J. Kanze) wrote:
>Today, at any rate; I'm
>more and more convinced that there is a way of rigorously reasoning
>about program correction based on object state, rather than program
>flow, although I've yet to seen anyone explain it.  (And of course,
>reasoning about program correction based on object state pretty much
>eliminates the objections to exceptions.)

As understand it, one can prove a program "correct" only with
respect to a specification, and only by reasoning about program
flow.  However:

  "Just because a program is 'proven correct' ... you cannot be
   sure it will do what you intend."

     -- Brian Cantwell Smith, "The Limits of Correctness,"
     Proceedings of the Symposium on Unintentional Nuclear War,
     Fifth Congress of the International Physicians for the
     Prevention of Nuclear War, 1985

The problem with correctness proofs is that they are only as
good as the specification, and say nothing about how much
damage a program might do if the specification turns out
to be wrong.  So I say that if safety requires correctness
no language is safe enough.

However, exception safety in C++ and similar languages does
not depend on analyzing all possible program flows, but rather
on designing code such that no matter what control path is
taken the invariants of object state are maintained.  In my
experience exception specifications beyond throw() are not of
much help in such design.

Greg Colvin


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/19
Raw View
Drew Hall <ahall@nospam.thevine.net> writes:

|>  AllanW@my-dejanews.com wrote:
|>
|>  > > |>  WHY does this scare you? Would you feel more secure if they were
|>  > > |>  forced to use Ada? Assembly language? Java? COBOL? BASIC?
|>  > > |>
|>  > > |>  What is the One Truely Safe Language that wouldn't scare you?
|>
|>  > May I suggest an alternative? Write a test program that uses new features.
|>  > Write a LOT of test programs, using ALL the new feature in EVERY
|>  > conceivable way. For each test program, write down the expected results
|>  > before you execute the program. Now compile and execute the test
|>  > programs on as wide of a variety of "compliant" compilers as you can.
|>
|>  Good idea.  That's why they use Ada.  Ada compilers have to be "validated,"
|>  and the validation process is just that--a body of some ungodly number of
|>  small programs that ANSI/ISO/USDOD has determined can conclusively prove if an
|>  implementation is correct.  So all you have to do for your safety critical
|>  project is make sure you see the Pentagon shaped sticker on the compiler box.

If you trust the Pentagon:-).

Seriously, you CAN do the same for C++.  Both Perenial and Plum-Hall
have extensive test suites; I've used the Perenial one in the distant
past, with interesting results.

None of them, of course, prove that there are no bugs in the compiler,
or that some strange combination of features will not cause problems.
On one (not safety critical) project, we experienced significant
problems with the compiler inserting the wrong virtual function in the
vtbl.  The problem only occured in the case of very complex inheritance
hierarchies, and not in the test suites.  On the other hand, it occured
with all compilers we tried at that time, with the exception of CFront.
This is now ancient history; the problem completely disappeared with
g++ 2.7.2, and I imagine that it is also gone from the commercial
compilers.  However: the test suites all said that all of the compilers
handled multiple inheritance and virtual base classes correctly.  They
did, but not all of the time.

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orient   e objet --
              -- Beratung in objektorientierter Datenverarbeitung


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/20
Raw View
AllanW@my-dejanews.com writes:

|>  In article <m3hfxkqyho.fsf@gabi-soft.fr>,
|>    kanze@gabi-soft.fr (J. Kanze) wrote:
|>  > Well, for one, one should certainly be afraid if they are using a
|>  > language that isn't stable (like C++ or Java -- or Basic!), since you
|>  > are almost by definition using an unstable compiler.
|>
|>  I must ask your definition of "stable." FWIW, my personal definition
|>  of a stable language is one which is well-defined and well-understood;
|>  this would include any with ANSI and/or ISO definitions, such as C++.

An important part of the definition of "stable", as far as I know, is an
absence of change.  This would hardly apply to C++ in recent years. I
think that we can now refer to standard C++ as a stable language.
Regretfully, there aren't any compilers available for standard C++ just
yet, so I have to use a slightly different language, which is NOT
stable.  (I rather like Nathan Meyer's characterization, that none of
the compilers currently available are mature.)

I think your adjunctions of well-defined and well-understood are also
useful, although I wouldn't traditionally have associated them with the
adjective "stable".  Having had to interview candidates for the post of
C++ programmer a couple of months ago, I have my doubts about the "well
understood" part, applied to C++.  Although to be honest, IMHO, the
parts of the language I was asking about are well understood, or at
least, should be.  (95% of the candidates had never heard of a virtual
destructor.  The need for a virtual destructor is hardly a result of any
recent changes in the language.)

Finally, I would like to ask you to consider my comment in its context.
I explicitly said that the use of C++ (or any other language) per se
would not scare me.  C++ (or any other language) is really an infinite
number of languages, since in any one project, I can limit myself to a
fully conformant subset.  And despite what some detractors might say,
there exist highly usable subsets of C++ which are very stable ; if you
avoid nesting classes, I suspect that 99% of the programs written for
CFront 2.0 will compile and run with today's compilers (provided the
compiler has a switch for the old for scope, of course).  And CFront 2.0
goes back a long way.

|>  Your objection seems to refer to unstable compilers, rather than
|>  unstable languages. But it also seems to contrast "a Java compiler"
|>  with "a C++ compiler", so perhaps it really is about languages
|>  after all.

If the language is "unstable", the compilers for it are almost by
definition "unstable".  The point is simple, the language compiled by
currently available C++ compilers changes with each new release.

|>  > It would be nice to think that the language chosen allowed efficient
|>  > reasoning about program logic.
|>
|>  Naturally. And they all do, except that each one has at least one
|>  strength not seen in other languages (if this were not so, there
|>  would be no reason to invent a new language).

I wonder if you've ever written (or read) Fortran IV :-).

In fact, cleanly written C++ isn't too bad when it comes to reasoning
about program logic.  The only real complaint is that it is so easy to
slip, and not be as clean as one would like.  (Note that this is a
relative criteria.  It is possible to write illogical programs in any
language, despite Bertrand Meyer's claims for Eiffel.  And one of the
most cleanly written programs I ever saw was written in Fortran IV.
Never the less, I think it safe to say that different languages
"encourage" clean writing more than others, and that C++ is,
regretfully, one that encourages it less than many others.)

|>  > Of course, this can be achieved as well
|>  > by eliminating the particular constructs which create the difficulties;
|>  > a great deal of critical programming is done in Ada, for example, but it
|>  > is generally a project rule to forbid the use of exceptions.
|>  >
|>  > Other than that, the simpler the language, the better, as it increases
|>  > the chances that the compiler writer got it right.  (Given that Ada is
|>  > generally the language of choice, however, one wonders.)  On the other
|>  > hand, too much simplicity (i.e. assembler) is just pushing the problem
|>  > into the hands of the programmer.  Of course, simplicity or
|>  > orthogonality is also increases the chances that the programmer
|>  > understands the language well enough so that his code does what he
|>  > thinks it does.
|>
|>  Well, of the six languages mentioned at the top of this note, you have
|>  dismissed four. The sentence in parens above seems to cast dispersions
|>  on Ada as well, leaving COBOL unscathed, winner by default. Clearly, as
|>  one of the first two "high-level" languages, it can claim the title of
|>  Stable.

Have you seen the latest version of the COBOL standard:->?  (Also, it
isn't one of the first two "high-level" languages, as at least Fortran
and Lisp predate it.)

Actually, if I didn't mention COBOL, it was because it seemed self
evident to me that it doesn't even come close to meeting the reasoning
about program logic criteria.

|>  Or can it? COBOL has been changing every few years, just as Ada and C
|>  and now C++ have been changing. Naturally, one goal is backwards
|>  compatibility; like C, they have been mostly but not completely
|>  successful in that goal.
|>
|>  In any case, I doubt you will convince me that a 20,000-line COBOL
|>  program is better for "safety critical systems" than a 6,000-line
|>  C++ programmer, given similar working conditions (i.e. experience of
|>  coders and testers, detailed specs, test scripts, etc.).

I wouldn't even try.  I might, however, consider that a 10000 line Ada
program would probably be superior than a 6000 line C++ one.

However, your "conditions" are the real key.  Writing safety critical
applications is a specialty in its own right, and more important than
the language is getting people qualified in this specialty.  Just
knowing C++ (or Ada, or whatever) isn't enough.  And most of the
literature concerning C++ is NOT critical system oriented.

|>  > Globally, I wouldn't be afraid if I learned they were using C++, per se.
|>  > I would be afraid if I found out they were using all of the most recent
|>  > features of the language -- for really safety critical systems, I'd
|>  > probably limit myself to the subset supported by CFront 2.1, although I
|>  > can imagine that allowing very simple templates (e.g. those that use no
|>  > other tempates in their implementation) might be acceptable.
|>
|>  Hmmm. A "naive" policy would be to use language features whenever they
|>  help to solve a problem, and to avoid using them at all other times
|>  (i.e. avoid using "pointer to member" for reasons such as "show the
|>  other programmers who's the real hot-shot).
|>
|>  You propose a different policy -- one that forbids "new" features --
|>  presumably spelled out somewhere, and applied to all programmers on
|>  the project. On the surface, this sounds extremely reasonable. But
|>  recognize that all of the CFront features were once brand-spankin'-new
|>  features too, so there MUST be some way that a new "unsafe" feature
|>  becomes an old "safe" feature in your mind. The obvious, but least
|>  logical method, would be the passage of time.

Use.  Not all systems are safety critical.  I prefer to let the new
features acquire the experience necessary to become old features in less
safety critical systems, that's all.

This applies to all languages, not just C++.  I know of at least one
very large critical application which is moving from Ada (83) to C++.
Because they want to use an OO paradigm, and the OO support
(inheritance) in C++ is more "stable" (older) than that in Ada '95.
They are still very much in the early stages, but I imagine that they
will eschew many of the more modern features, and probably the entire
STL, on the grounds of their being too new and unstable.

|>  May I suggest an alternative? Write a test program that uses new features.
|>  Write a LOT of test programs, using ALL the new feature in EVERY
|>  conceivable way. For each test program, write down the expected results
|>  before you execute the program. Now compile and execute the test
|>  programs on as wide of a variety of "compliant" compilers as you can.
|>  Examine the actual results and compare them to the expected results.

Do you have any idea how much work it would be to do that.  Perenial
(and others) have such suites available.  I know of no compiler which
passes all of the tests in the Perenial test suite.

|>  Each difference will result in either a documented issue with the vendor,
|>  or with a heightened awareness of the way that the feature really does
|>  (or does not) work. Generally, each difference will also result in one
|>  or more of the following:
|>      * A document that describes a limit of the new feature, either in
|>        the language or at least in certain compilers (frankly, you don't
|>        have to know which one -- the point is to avoid using the feature
|>        in this certain way)
|>      * A new test program to test your revised understanding of the new
|>        feature
|>      * A new test program to discover and document the precise extent
|>        of the compiler bug, or
|>      * A compiler patch to fix the error you have found (and then you will
|>        re-run your entire test suite against the patched compiler)
|>
|>  At some point, you will know enough about the feature and also about
|>  how well it works on your real compiler, that you should have no
|>  policy against using it whenever it really does solve a problem.
|>
|>  > And of course, the constraints concerning reasoning about the program
|>  > mean that some constructs will always be avoided: goto, exceptions, and
|>  > probably things like template specialization.
|>
|>  Does "goto" make a program unstable?

Anything that violates the single entrance/single exit principle makes
reasoning about program correctness more difficult.

|>  > Today, at any rate; I'm
|>  > more and more convinced that there is a way of rigorously reasoning
|>  > about program correction based on object state, rather than program
|>  > flow, although I've yet to seen anyone explain it.  (And of course,
|>  > reasoning about program correction based on object state pretty much
|>  > eliminates the objections to exceptions.)
|>
|>  The two are intertwined, perhaps two sides of the same coin. Surely
|>  program flow depends on the state (i.e. the contents of variables),
|>  and object state depends on program flow (try describing the state of
|>  even the simplest program, without telling which line will be executed
|>  next and/or what the "return stack" contains).
|>
|>  At any rate, none of these apply to C++ any more or any less than
|>  other languages, from the highest levels to the lowest levels.

The criteria apply equally to all languages.  For some of them
(stability, for example, or expressiveness), a subset of C++ ranks very
high.  For others (support for reasoning about program correctness), C++
is only in the middle of the pack.  And of course, these are only some
of the relevant criteria: the availability of a more or less stable
compiler for all of the platforms concerned, or the availability of
people who know the language well enough to know its pitfalls, are also
critical issues.

This last issue is often underestimated.  I happen to like Modula-3 a
lot, for example.  However, suppose that it is all I think it is, and
that it only offers one or two small possibilities for misuse, compared
to, say, a hundred in C++.  I can still find more people who know C++
inside out, and avoid all hunderd of the danger spots in C++ almost
instinctively, than I can find people who can even spell Modula-3, much
less are aware of the one or two danger spots.  (This was, I believe,
the key motivation for the project cited above moving from Ada to C++.
A research for people with actual Ada '95 experience drew a blank.  A
research for people with C++ experience actually found several with
extensive experience in similar, safety critical systems.)

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orientie objet --
              -- Beratung in objektorientierter Datenverarbeitung
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1998/10/11
Raw View
David Bruce wrote:

[...]

> As I see it, there are three problems with exception specifications as presently
> defined in C++; unlike some of the other posters to this thread, however, I
> consider them repairable (see below) and -- once repaired -- extremely valuable.
>
> First, as others have noted, they are dangerous because they are not properly
> enforced -- at compile-time -- by the compiler, and so we have the spectre of
> terminate(), etc.  If they were treated like const in this respect, one could
> actually rely on them; if someone whose code we used changed an exception
> specification, we might have to change our own code in response, but at least we
> would know about it before it's too late.

Well, if the other problem were solved, this one would be trivial
indeed.

>
> Second, and most fundamental, is that templates are incapable of making the use
> of exception specifications fully generic.

[...]

> What is required here, but I believe templates (as currently formulated) to be
> incapable of supporting, is to make the function generic over a *list* (or set)
> of zero or more classes; this is as much a *syntactic* limitation as anything
> else.

This is indeed a limitation of templates; and it's a limitation I
already wanted to have removed, although for other reasons
(templated functions on varying typelists). The one could f.ex. write

template<class T> class Container
{
  vector<T> theData;
public:
  template<typelist Args> void add(Args const& args)
  {
    theData.push_back(T(args));
  }
};

Container<complex<double> > c;

c.add(3.5, 7.9);
// generates:
//   Container<complex<double> >::add<>(double const& args__1,
//                                      double const& args__2)
//   {
//     theData.push_back(complex<double>(args__1, args__2);
//   }

Generally such a mechanism would allow for typesafe variable argument
list functions.

> (Note that we would also need syntax for adding and subtracting
> classes/lists of classes from the list; the former to allow for several sources
> of exception, the latter to recognize the effect of exception handling.)  (If
> the idea of general "classlist" template parameters is considered too ambitious,
> go for exceptions only with "exnspec" instead.)  Twice could then be written as:
>
>     template <exnspec Exns>
>     int twice(int (*f)(int) throw(Exns), int x) throw(Exns) { return f(f(x)); }
>
> and a more involved example might look like:
>
>     class NegativeArg {};
>
>     template <exnspec Exns>
>     int nonneg(int (*f)(int) throw(Exns), int x) throw((Exns + NegativeArg) - BadArg)

+ and - don't look nice here; "adding" in exception specifyers is
already expressed with ","; "subtracting" could be done with a
special syntax like "~Type" (i.e. "throws not this type").

Your function declaration would then look like the following
(I'm using "typelist" for "exnspec"):

template<typelist Exns>
 int nonneg(int (*f)(int) throw(Exns), int x)
    throw(Exns, ~BadArg, NegativeArg)

One could define that ~Exception always overrides Exception.
The specification above would then be read as: "May throw anything
f throws except BadArg, and in addition NegativeArg."

>     {
>         try {
>             if (x < 0) { return f(x); } else { throw NegativeArg(); }
>         }
>       catch (BadArg) { ... }
>     }
>
> This should suffice for (templated) library classes (e.g., containers) too, at
> least with member templates.

Unfortunately, this is only solving part of the problem.
Most functions are not specialized on other functions, but on generic
types, where you would have to mention every single (possibly itself
templated) member function and every template function called
separately (which may get rather complicated if you are using
f.ex. template expressions).

Moreover, you might not even know which functions are actually called.
Consider f.ex. the following simple template:

template<class T>
 bool operator!=(T const& t1, T const& t2)
{
  return !(t1 == t2);
}

What functions may this invoke? Let's make a few calls.

Assume we have the following definitions:

class A {};
bool operator==(A const& a1, A const& a2);

class B { bool operator==(B const& b2) const; };

class C { C(C const&); };
bool operator==(C c1, C c2);

class D {};
class DeferredBool
{
  operator bool() const;
  DeferredBool operator!() const;
};
DeferredBool operator==(D const& d1, D const& d2);

class X5 {};
class Extreme { operator X5() const; };
class X1 { operator bool() const; }
class X2 { X2(X2 const&); };
class X3 { operator X2() const; };
class X4 { X4(Extreme const&); }
X1 operator!(X2);
X3 operator==(const X4&, const X5&);

A a1, a2;
B b1, b2;
C c1, c2;
D d1, d2;
Extreme e1, e2;
bool result;

Now we try a few calls to operator!=, and look at what get's called
inside that function:

result = (a1 != a2);
  // bool operator==(A const&, A const&)

result = (b1 != b2);
  // bool B::operator==(B const&) const

result = (c1 != c2);
  // C::C(C const&)
  // bool operator==(C, C)

result = (d1 != d2);
  // DeferredBool operator==(D const&, D const&)
  // DeferredBool DeferredBool::operator!() const
  // DeferredBool::operator bool() const

result = (e1 != e2);
  // X4::X4(Extreme const&)
  // Extreme::operator X5() const
  // X3 operator==(X4 const&, X5 const&)
  // X3::operator X2() const
  // X2::X2(X2 const&)  (for call-by-value in operator!)
  // X1 operator!(X2)
  // X1::operator bool() const

And now try to write an exception specification for the templated
operator!= which accounts for all of those cases (and all others
I might have forgotten ;-))

I guess looking at things like early/late binding or overloading of
templated and untemplated functions will uncover even more problems.

[...]

> So, to the C++ gurus out there, is there any reason something like the above
> couldn't be made to work?  What problems remain?

Many, see above ;-)

[...]

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Drew Hall <ahall@nospam.thevine.net>
Date: 1998/10/14
Raw View
AllanW@my-dejanews.com wrote:

> > |>  WHY does this scare you? Would you feel more secure if they were
> > |>  forced to use Ada? Assembly language? Java? COBOL? BASIC?
> > |>
> > |>  What is the One Truely Safe Language that wouldn't scare you?

> May I suggest an alternative? Write a test program that uses new features.
> Write a LOT of test programs, using ALL the new feature in EVERY
> conceivable way. For each test program, write down the expected results
> before you execute the program. Now compile and execute the test
> programs on as wide of a variety of "compliant" compilers as you can.

Good idea.  That's why they use Ada.  Ada compilers have to be "validated,"
and the validation process is just that--a body of some ungodly number of
small programs that ANSI/ISO/USDOD has determined can conclusively prove if an
implementation is correct.  So all you have to do for your safety critical
project is make sure you see the Pentagon shaped sticker on the compiler box.

Drew


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: kanze@gabi-soft.fr (J. Kanze)
Date: 1998/10/06
Raw View
AllanW@my-dejanews.com writes:

|>  > In article <3610CF6C.209F257F@acm.org>, Pete Becker
|>  <petebecker@acm.org>
|>  > writes
|>  > >Please write a function that calls f() and properly recovers from any
|>  > >exceptions that it throws. Incidentally, this is for a critical
|>  system
|>  > >on the space shuttle. Aborting the program is not acceptable.
|>
|>  In article <XNXA$GAKPeE2EwCJ@robinton.demon.co.uk>,
|>    Francis Glassborow <francisG@robinton.demon.co.uk> wrote:
|>  > What scares me is that people writing such safety critical systems
|>  could
|>  > consider using C++.
|>
|>  WHY does this scare you? Would you feel more secure if they were
|>  forced to use Ada? Assembly language? Java? COBOL? BASIC?
|>
|>  What is the One Truely Safe Language that wouldn't scare you?

Well, for one, one should certainly be afraid if they are using a
language that isn't stable (like C++ or Java -- or Basic!), since you
are almost by definition using an unstable compiler.

It would be nice to think that the language chosen allowed efficient
reasoning about program logic.  Of course, this can be achieved as well
by eliminating the particular constructs which create the difficulties;
a great deal of critical programming is done in Ada, for example, but it
is generally a project rule to forbid the use of exceptions.

Other than that, the simpler the language, the better, as it increases
the chances that the compiler writer got it right.  (Given that Ada is
generally the language of choice, however, one wonders.)  On the other
hand, too much simplicity (i.e. assembler) is just pushing the problem
into the hands of the programmer.  Of course, simplicity or
orthogonality is also increases the chances that the programmer
understands the language well enough so that his code does what he
thinks it does.

Globally, I wouldn't be afraid if I learned they were using C++, per se.
I would be afraid if I found out they were using all of the most recent
features of the language -- for really safety critical systems, I'd
probably limit myself to the subset supported by CFront 2.1, although I
can imagine that allowing very simple templates (e.g. those that use no
other tempates in their implementation) might be acceptable.

And of course, the constraints concerning reasoning about the program
mean that some constructs will always be avoided: goto, exceptions, and
probably things like template specialization.  Today, at any rate; I'm
more and more convinced that there is a way of rigorously reasoning
about program correction based on object state, rather than program
flow, although I've yet to seen anyone explain it.  (And of course,
reasoning about program correction based on object state pretty much
eliminates the objections to exceptions.)

--
James Kanze    +33 (0)1 39 23 84 71    mailto: kanze@gabi-soft.fr
GABI Software, 22 rue Jacques-Lemercier, 78000 Versailles, France
Conseils en informatique orientie objet --
              -- Beratung in objektorientierter Datenverarbeitung
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: AllanW@my-dejanews.com
Date: 1998/10/07
Raw View
In article <3610CF6C.209F257F@acm.org>,
Pete Becker <petebecker@acm.org> wrote:
> |>  > >Please write a function that calls f() and properly recovers
> |>  > >from any exceptions that it throws. Incidentally, this is
> |>  > >for a critical system on the space shuttle. Aborting the
> |>  > >program is not acceptable.

In article <XNXA$GAKPeE2EwCJ@robinton.demon.co.uk>,
Francis Glassborow <francisG@robinton.demon.co.uk> wrote:
> |>  > What scares me is that people writing such safety critical
> |>  > systems could consider using C++.

I, AllanW@my-dejanews.com wrote:
> |>  WHY does this scare you? Would you feel more secure if they were
> |>  forced to use Ada? Assembly language? Java? COBOL? BASIC?
> |>
> |>  What is the One Truely Safe Language that wouldn't scare you?

In article <m3hfxkqyho.fsf@gabi-soft.fr>,
  kanze@gabi-soft.fr (J. Kanze) wrote:
> Well, for one, one should certainly be afraid if they are using a
> language that isn't stable (like C++ or Java -- or Basic!), since you
> are almost by definition using an unstable compiler.

I must ask your definition of "stable." FWIW, my personal definition
of a stable language is one which is well-defined and well-understood;
this would include any with ANSI and/or ISO definitions, such as C++.

Your objection seems to refer to unstable compilers, rather than
unstable languages. But it also seems to contrast "a Java compiler"
with "a C++ compiler", so perhaps it really is about languages
after all.

> It would be nice to think that the language chosen allowed efficient
> reasoning about program logic.

Naturally. And they all do, except that each one has at least one
strength not seen in other languages (if this were not so, there
would be no reason to invent a new language).

> Of course, this can be achieved as well
> by eliminating the particular constructs which create the difficulties;
> a great deal of critical programming is done in Ada, for example, but it
> is generally a project rule to forbid the use of exceptions.
>
> Other than that, the simpler the language, the better, as it increases
> the chances that the compiler writer got it right.  (Given that Ada is
> generally the language of choice, however, one wonders.)  On the other
> hand, too much simplicity (i.e. assembler) is just pushing the problem
> into the hands of the programmer.  Of course, simplicity or
> orthogonality is also increases the chances that the programmer
> understands the language well enough so that his code does what he
> thinks it does.

Well, of the six languages mentioned at the top of this note, you have
dismissed four. The sentence in parens above seems to cast dispersions
on Ada as well, leaving COBOL unscathed, winner by default. Clearly, as
one of the first two "high-level" languages, it can claim the title of
Stable.

Or can it? COBOL has been changing every few years, just as Ada and C
and now C++ have been changing. Naturally, one goal is backwards
compatibility; like C, they have been mostly but not completely
successful in that goal.

In any case, I doubt you will convince me that a 20,000-line COBOL
program is better for "safety critical systems" than a 6,000-line
C++ programmer, given similar working conditions (i.e. experience of
coders and testers, detailed specs, test scripts, etc.).

> Globally, I wouldn't be afraid if I learned they were using C++, per se.
> I would be afraid if I found out they were using all of the most recent
> features of the language -- for really safety critical systems, I'd
> probably limit myself to the subset supported by CFront 2.1, although I
> can imagine that allowing very simple templates (e.g. those that use no
> other tempates in their implementation) might be acceptable.

Hmmm. A "naive" policy would be to use language features whenever they
help to solve a problem, and to avoid using them at all other times
(i.e. avoid using "pointer to member" for reasons such as "show the
other programmers who's the real hot-shot).

You propose a different policy -- one that forbids "new" features --
presumably spelled out somewhere, and applied to all programmers on
the project. On the surface, this sounds extremely reasonable. But
recognize that all of the CFront features were once brand-spankin'-new
features too, so there MUST be some way that a new "unsafe" feature
becomes an old "safe" feature in your mind. The obvious, but least
logical method, would be the passage of time.

May I suggest an alternative? Write a test program that uses new features.
Write a LOT of test programs, using ALL the new feature in EVERY
conceivable way. For each test program, write down the expected results
before you execute the program. Now compile and execute the test
programs on as wide of a variety of "compliant" compilers as you can.
Examine the actual results and compare them to the expected results.
Each difference will result in either a documented issue with the vendor,
or with a heightened awareness of the way that the feature really does
(or does not) work. Generally, each difference will also result in one
or more of the following:
    * A document that describes a limit of the new feature, either in
      the language or at least in certain compilers (frankly, you don't
      have to know which one -- the point is to avoid using the feature
      in this certain way)
    * A new test program to test your revised understanding of the new
      feature
    * A new test program to discover and document the precise extent
      of the compiler bug, or
    * A compiler patch to fix the error you have found (and then you will
      re-run your entire test suite against the patched compiler)

At some point, you will know enough about the feature and also about
how well it works on your real compiler, that you should have no
policy against using it whenever it really does solve a problem.

> And of course, the constraints concerning reasoning about the program
> mean that some constructs will always be avoided: goto, exceptions, and
> probably things like template specialization.

Does "goto" make a program unstable?

> Today, at any rate; I'm
> more and more convinced that there is a way of rigorously reasoning
> about program correction based on object state, rather than program
> flow, although I've yet to seen anyone explain it.  (And of course,
> reasoning about program correction based on object state pretty much
> eliminates the objections to exceptions.)

The two are intertwined, perhaps two sides of the same coin. Surely
program flow depends on the state (i.e. the contents of variables),
and object state depends on program flow (try describing the state of
even the simplest program, without telling which line will be executed
next and/or what the "return stack" contains).

At any rate, none of these apply to C++ any more or any less than
other languages, from the highest levels to the lowest levels.

--
AllanW@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: abrahams@spam.motu.com (David Abrahams)
Date: 1998/10/08
Raw View
On 6 Oct 1998 09:06:47 -0400, kanze@gabi-soft.fr (J. Kanze) wrote:

>Today, at any rate; I'm
>more and more convinced that there is a way of rigorously reasoning
>about program correction based on object state, rather than program
>flow, although I've yet to seen anyone explain it.  (And of course,
>reasoning about program correction based on object state pretty much
>eliminates the objections to exceptions.)

James has been asking to see some formal work in this area for some
time. Happily, I may finally be able to help. After a talk I gave on
exception-safety in generic components, one of the more
theoretically-minded attendees (Gary Leavens) offered to send me some
references to previously published work. I haven't had a chance to
follow his leads yet, but here they are, for anyone who's interested

-Dave

-------
Subject:     references on exception handling

Here's the references about exceptions that I was telling you about.
The work of Bertrand Meyer is the most closely related to your talk.

Gary

@Article{Meyer92a,
Key =  "Meyer",  Author =  "Bertrand Meyer",  Title =
"Applying ``Design by Contract''",  Journal =  "Computer",  Year =
1992,  Volume =  25,  Number =  10,  Month =  Oct,  Pages =
"40-51",  Annote =  "10 references."}

In the book, look up exceptions in the index...

@Book{Meyer97, Key="Meyer",Author="Bertrand
Meyer",Title="Object-oriented Software
Construction",Publisher="Prentice
Hall",Edition="second",Address=NY,Year=1997,Annote="The programming
language Eiffel."}

@Article{Liskov-Snyder79, Key="Liskov \& Snyder",Author="Barbara H.
Liskov and Alan Snyder",Title="Exception Handling in
CLU",Journal="IEEE Transactions on Software
Engineering",Year=1979,Volume="SE-5",Number=6,Month=Nov,Pages="546-558",Annote="Describes
the exception handling mechanism in CLU. Gives rationale for
the termination model and an implementation. 9 references."}

I'm not sure how relevant the following is...@Article{Szczepanska91,
Key =  "Szczepanska",  Author =  "Danuta Szczepanska",  Title =
"A Hoare-like verification system for a language with   an
exception handling mechanism",  Journal =  TCS,  Year =  1991,
Volume =  80,  Number =  2,  Month =  Mar,  Pages =
"319-335"}


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: abell8920@mindspring.com (Andrew Bell)
Date: 1998/10/08
Raw View
On 24 Sep 1998 18:02:16 GMT, Francis Glassborow
<francis@robinton.demon.co.uk> wrote:
>As regards templates, there are serious problems and with the growth of
>generic programming I think we must either seriously consider throwing
>out exception specifications or we must examine ways in which they can
>be supported in templates [...]

If we make the giant leap and assume that exception specs are checked
at compile time, it seems to me templates may not be a problem, at
least when the whole template is provided in headers.  If you think of
templates as a kind of "magic macro", in a sense it's generally just
additional lines of code in the non-template functions that make use
of them, as you can use the template definition in your static
analysis.

For example, using the standard templated != function
template <class Type> bool operator!=(const Type& x, const Type& y)
{
 return !(x==y);
}

If you have a (nonsense) function

bool f() throw()
{
 Foo x, y;

 return x != y;
}

To do static analysis of exceptions, the compiler doesn't need a spec
on the template, it can just look at the template definition, which
calls operator==() on two Foos.  So if the Foo constructor can't
throw, and that operator==() can't throw, we're in fine shape.

We might run into problems with explicit instantiation, however, and
I'm not sure quite how this works.  Do you need a declaration for an
explicit specialization for a class before making use of it?  If not,
will it use an unspecialized form?  Likewise, if in the above code,
after the above lines, we have

bool operator!=(const Foo& foo1, const Foo& foo2) throw(bar) {...}

Will this function be used in preference to the template?  Is this a
compile error?

Andrew Bell


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: ajenkins@javanet.com
Date: 1998/10/08
Raw View
In article <6vdq0e$gau$1@nnrp1.dejanews.com>,
  AllanW@my-dejanews.com wrote:

Your response seems pretty disingenuous to me.

> Hmmm. A "naive" policy would be to use language features whenever they
> help to solve a problem, and to avoid using them at all other times
> (i.e. avoid using "pointer to member" for reasons such as "show the
> other programmers who's the real hot-shot).
>
> You propose a different policy -- one that forbids "new" features --
> presumably spelled out somewhere, and applied to all programmers on
> the project. On the surface, this sounds extremely reasonable. But

I think it's clear what the limit he was talking about was.  The fact is that
there are no compilers that currently implement all of standard C++, and
their support of newer features is often buggy.  So it makes perfect sense to
avoid using standard language features that are known to be generally not
well implemented in current compilers in a critical program.  Just pointing
out that the line between "new" and "old" features is a little fuzzy doesn't
change this basic observation at all.

> > And of course, the constraints concerning reasoning about the program
> > mean that some constructs will always be avoided: goto, exceptions, and
> > probably things like template specialization.
>
> Does "goto" make a program unstable?

He didn't say anything here about stability.  He said it makes programs hard
to reason about, which is true in general because of the unrestricted nature
of goto.

--
Adam P. Jenkins
ajenkins@javanet.com

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1998/10/09
Raw View
Andrew Bell wrote:

[...]

> To do static analysis of exceptions, the compiler doesn't need a spec
> on the template, it can just look at the template definition, which
> calls operator==() on two Foos.  So if the Foo constructor can't
> throw, and that operator==() can't throw, we're in fine shape.

However, as soon as the compilers implement the export keyword,
there will be templates which cannot be effectively checked at
compile time. Of course, we could pass the information to the linker
and check at link time.

[...]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/10/02
Raw View
In article <3610CF6C.209F257F@acm.org>, Pete Becker <petebecker@acm.org>
writes
>Please write a function that calls f() and properly recovers from any
>exceptions that it throws. Incidentally, this is for a critical system
>on the space shuttle. Aborting the program is not acceptable.

What scares me is that people writing such safety critical systems could
consider using C++.



Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: AllanW@my-dejanews.com
Date: 1998/10/03
Raw View
> In article <3610CF6C.209F257F@acm.org>, Pete Becker
<petebecker@acm.org>
> writes
> >Please write a function that calls f() and properly recovers from any
> >exceptions that it throws. Incidentally, this is for a critical
system
> >on the space shuttle. Aborting the program is not acceptable.

In article <XNXA$GAKPeE2EwCJ@robinton.demon.co.uk>,
  Francis Glassborow <francisG@robinton.demon.co.uk> wrote:
> What scares me is that people writing such safety critical systems
could
> consider using C++.

WHY does this scare you? Would you feel more secure if they were
forced to use Ada? Assembly language? Java? COBOL? BASIC?

What is the One Truely Safe Language that wouldn't scare you?

--
AllanW@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----------== Posted via Deja News, The Discussion Network ==----------
http://www.dejanews.com/       Search, Read, Discuss, or Start Your Own



      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: obricker@my-dejanews.com
Date: 1998/09/29
Raw View
In article <360E3384.FF761CF0@acm.org>,
  Pete Becker <petebecker@acm.org> wrote:
> obricker@my-dejanews.com wrote:
> >
> > > In practice, I have found that most functions should _not_ provide a throw
> > > specification and that the majority of those that do should provide an
empty
> > > one.
> > >
> >
> > I want a way to know what exceptions a function might throw. How else am I
to
> > know what to look for to catch and recover from?
>
> By reading the documentation. Even with mandatory exception
> specifications you have to do this: knowing that a function throws a
> particular exception does not tell you under what circumstances that
> exception can be thrown, so you must read the documentation in order to
> understand how to respond to that exception.
>

My point in this post and in my others is that the exception specification
provides that documentaion and acts as a contract with the calling function.
Compilers should provide warnings when you fail to handle these possible
results by catching or providing your own exception spec (sub-contracting?).

I can imaging a project involving multiple programmers where one might add
something to the exceptions thrown by a function. While proper communication
will ensure that all users are informed about the change, it would be even
better if the compiler also warned of the new syntax.

Otis B.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: AllanW@my-dejanews.com
Date: 1998/09/29
Raw View
In article <6u801d$dcg$1@nnrp1.dejanews.com>,
  agriffiths@ma.ccngroup.com wrote:
>
> In article <$NdKfQAziOA2EwHa@robinton.demon.co.uk>,
>   Francis Glassborow <francis@robinton.demon.co.uk> wrote:
> > Now the problem is persuading the majority that they should provide
> > exception specs (it is so easy not to).
>
> "Common sense" does indeed suggest that exception specs should be the norm.
> However, this approach causes problems:
>
> 1/
> It leads to "unexpected & terminate" being invoked at runtime when exceptional
> problems occur - and a graceless exit from your application.  In many systems
> this is undesirable.
>
> 2/ It is difficult to maintain exception specifications during the lifetime
> of the project.
>
> 3/
> It greatly complicates the writing of templates.
>
> The above points derive from my experience, the Taligent guidelines and from
> communication on usenet.
>
> In practice, I have found that most functions should _not_ provide a throw
> specification and that the majority of those that do should provide an empty
> one.
>
> I can envisage exceptions: for example a stable API might helpfully provide
> more discriminating exception specs, but I've yet to see it in practice.

The company I work for agrees, and I think that I do too.

So far, we use exceptions in only a very limited way. We've been very
pleased with the way it can simplify our logic, making the program
more readable and maintainable and often smaller as well.

Naturally, each possible throw statement has a particular purpose. If
function foo() throws exception bar, presumably the intent is to allow
higher-level code to catch and deal with the situation, without a lot
of messy code obscuring the primary purpose of foo(). If programs call
foo() without recognizing the possible bar exception, then the
mechanism would work against us instead of for us. So documentation is
VERY important.

HOWEVER, the throw-specification doesn't seem to be helpful. All it
does is to guarantee that if foo() (or something that foo() calls)
should happen to throw something ELSE, we call unexpected(). It may
well be that the program calling foo() was aware of a possible
exception, even though foo() was not. (This can happen, for
instance, if a class type was passed to foo, and the class has a
virtual member, and derived classes override the member with one
that can throw.)
    void foo(MyClass *m) throw(baz) {
        m->func1();
        // What happens if func1() throws bar instead of baz?
        // If we remove the throw(baz) spec above,
        //    then whoever called foo() can handle it.
        // But with throw(baz) in place, we call unexpected()
    }

We also assume that the overhead of such run-time checks is not zero.
Possibly the extra overhead is quite small, but we find even quite
small added overhead to be objectional unless we can see some value
in it. So far, the only value we've found is for documentation
purposes (for which
    // Throws BAR if the fleen isn't in the fleen-cache
seems adequate), and for catching grave program errors (and perhaps
reporting them in a customer-support-friendly manner). But without
the throw-specification, the BAR exception percolates up to main()
anyway, so grave program errors are normally caught somewhere
anyway.

Obviously, others have differing opinions; if that were not true,
then throw-specifications would never have made it into the C++
specification. But so far I'm oblivious to the reasons for these
opinions.

I'm willing to learn. Can someone provide an example where the
throw-specification does something useful, other than documentation
or catching major program errors that would be caught somewhere else
anyway?

--
AllanW@my-dejanews.com is a "Spam Magnet" -- never read.
Please reply in USENET only, sorry.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]




[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "Greg Colvin" <spam@me.not>
Date: 1998/09/29
Raw View
abrahams@motu.com wrote in article <6ub436$kt7$1@nnrp1.dejanews.com>...
> Anyway, there is one way I think the language could support us better in this
> regard. Since empty exception-specifications have been shown to make a
> difference to optimization, I'd like to be able to write an compile-time-
> enforced empty exception-specification, which required all called functions
> to either satisfy the exception-specification or be called from within a try
> block.

The idea was that a compiler should use exception specifications to
optimize exception handling code, so mismatched specs could cause
warnings that the optimization was not possible.

> Greg Colvin may be able to argue from his experience with Java that it's more
> annoying than useful, but from where I sit it seems like a good option to
> have.

I suspect it would not be that annoying, since I suspect that most
functions that throw() are either leaf functions or have a catch(...)
clause anyway.

Greg Colvin


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/29
Raw View
In article <6uov50$7s5$1@nnrp1.dejanews.com>, obricker@my-dejanews.com
writes
>I can imaging a project involving multiple programmers where one might add
>something to the exceptions thrown by a function.

Which leads back to my original guideline that member functions should
only throw exceptions based on std:exception and those based on a class
specific exception type.  Programmers who invent free standing exception
types are adding unnecessary problems.


>

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: Pete Becker <petebecker@acm.org>
Date: 1998/09/29
Raw View
obricker@my-dejanews.com wrote:
>
> In article <360E3384.FF761CF0@acm.org>,
>   Pete Becker <petebecker@acm.org> wrote:
> > By reading the documentation. Even with mandatory exception
> > specifications you have to do this: knowing that a function throws a
> > particular exception does not tell you under what circumstances that
> > exception can be thrown, so you must read the documentation in order to
> > understand how to respond to that exception.
> >
>
> My point in this post and in my others is that the exception specification
> provides that documentaion and acts as a contract with the calling function.

Then you are simply wrong.

class Error;

void f() throw(Error);

Please write a function that calls f() and properly recovers from any
exceptions that it throws. Incidentally, this is for a critical system
on the space shuttle. Aborting the program is not acceptable.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/24
Raw View
In article <6u801d$dcg$1@nnrp1.dejanews.com>, agriffiths@ma.ccngroup.com
writes
>3/
>It greatly complicates the writing of templates.
>
>The above points derive from my experience, the Taligent guidelines and from
>communication on usenet.
>
>In practice, I have found that most functions should _not_ provide a throw
>specification and that the majority of those that do should provide an empty
>one.
>
>I can envisage exceptions: for example a stable API might helpfully provide
>more discriminating exception specs, but I've yet to see it in practice.

Curiously, I was one of those (within the UK) who wanted them removed
(not included) in the language because I believed they were not able to
provide any real benefit:)

As regards templates, there are serious problems and with the growth of
generic programming I think we must either seriously consider throwing
out exception specifications or we must examine ways in which they can
be supported in templates (I need to be able to place some sort of
exception spec on a class template that can be provided at the
instantiation point.  Perhaps we should also consider exception specs
for a whole class.

Please note that I am speculating here. And so ideas are good but
screaming at me isn't (I hope)



Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: abrahams@motu.com
Date: 1998/09/24
Raw View
In article <46i7ifALm5B2Ew9J@robinton.demon.co.uk>,
  Francis Glassborow <francisG@robinton.demon.co.uk> wrote:

> I certainly respect your opinion but it serves to make clear a serious
> issue that, I believe, can only currently be resolved by implementors.
> I know of no way to write code that will meet the needs of the 'no
> exception specification' school and also work with those wanting them.

That's true, but what do you want them *for*? As I tried to point out in a
previous post, if you maintain them religiously, all you get for your hard
work is documentation. If you slip up, you're repaid with unexpected
termination at runtime, when an error occurs... a very difficult debugging
scenario. We do, in fact, have a way to write code that meets the needs of
those who want to document every exception that can be thrown by a function:
it begins with // ;)

> We cannot eve produce a hack with the preprocessor (not valid in C++,
> but I have seen someone remove all uses of const from C code with
> #define const
>
> (doesn't work in C++ for several reasons)
>
> What is needed (to meet both schools of style) is a compiler switch that
> suppresses the effects of exception specifications.

With all due respect, the "school of style" that wants to put exception
specifications everywhere is, for nearly all applications, simply wrong. I
don't want to make it compatible with the other approach. I'm searching for a
good analogy... the best I can come up with now is a "style" that makes all
data members public and refers to them from outside a class. Both styles lead
to unmaintainable and dangerous code.

> I suspect that as programmers become more used to ES they will come to
> use them

I hope they will only use them sparingly and with great caution!

>(just as many more C programmers use const as a result of
> exposure to const in C++, those exposed to ES in Java may eventually
> decide they like it -- of course they might not).

Your analogy doesn't work at all. The great advantage of const is that the
compiler gives you something you can brace yourself against. It enforces at
compile time that you're doing the right thing. Of course you can undermine
that enforcement, but a conscientious programmer does not. Unless your
implementation actually puts const objects in read-only memory, even
undermining const is usally not catastrophic. With exception-specifications,
it's more like running naked across enemy lines and hoping nobody shoots you.
If your function has an exception-specification and it calls someone else's
function, you've just have to hope that they don't decide to throw something
new next week.

More precisely, your style says something like "I can fire these three kinds
of weapon, and although I may have been utterly invulnerable to attack from
any kind of weapon at all, I VOLUNTEER TO COMMIT SUICIDE if anyone should
fire anything at me other than these three I've listed". Sorry for the
military analogies, but they just seem to fit.

> In general application programmers (component assemblers) can ignore ES
> if they wish.  The big impact is on those deriving from base classes and
> those using templates.

Yes, and because of the dangers I've described I hope that people generally
eschew exception-specifications on templates and base classes (except,
perhaps, for destructors).

> Once upon a time C production code religiously compiled with #define
> NDEBUG to suppress uses of assert.  This is no longer uniformly the case
> as some programmers have decided that leaving the asserts in production
> code meets some safety critierion.  I would be happy to see a #define
> NO_ES available.  I would be even happier if this became portable.

It's not clear to me whether you think NO_ES would be analgous to #define
NDEBUG or #undef NDEBUG.

Anyway, there is one way I think the language could support us better in this
regard. Since empty exception-specifications have been shown to make a
difference to optimization, I'd like to be able to write an compile-time-
enforced empty exception-specification, which required all called functions
to either satisfy the exception-specification or be called from within a try
block.

Greg Colvin may be able to argue from his experience with Java that it's more
annoying than useful, but from where I sit it seems like a good option to
have.

-Dave




-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/24
Raw View
In article <6ub436$kt7$1@nnrp1.dejanews.com>, abrahams@motu.com writes
>Anyway, there is one way I think the language could support us better in this
>regard. Since empty exception-specifications have been shown to make a
>difference to optimization, I'd like to be able to write an compile-time-
>enforced empty exception-specification, which required all called functions
>to either satisfy the exception-specification or be called from within a try
>block.

I wish you had been around when I and the UK were arguing that exception
specifications should not be part of C++

The argument on the other side at that time was that they would be
useful as tools became available to do static analysis based on them.
What you are saying is that what we have now is unusable.  If we follow
that logic we should deprecate them as soon as possible.  What I am
saying is that I would love implementors to generally agree to provide a
switch that results in them being completely ignored and having zero
impact on code.  That would ensure that the runtime breach and terminate
were avoided in production code while allowing their use in debugging
environments which had static analisers.


>
>Greg Colvin may be able to argue from his experience with Java that it's more
>annoying than useful, but from where I sit it seems like a good option to
>have.

I agree.  I think Greg is suffering from naive code that does not have a
well thought out policy for using exceptions specifications.  I.e. the
language is immature:)

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: abrahams@spam.motu.com (David Abrahams)
Date: 1998/09/24
Raw View
On 24 Sep 1998 20:04:33 GMT, Francis Glassborow
<francis@robinton.demon.co.uk> wrote:

>I wish you had been around when I and the UK were arguing that exception
>specifications should not be part of C++
>
>The argument on the other side at that time was that they would be
>useful as tools became available to do static analysis based on them.

I'd be interested to know in more detail what tools were envisioned
and how they would make exception-specifications useful.

>What you are saying is that what we have now is unusable.

I don't presume quite that much; all I'm saying is that I have thought
long and hard about the issue and haven't been able see any way that
they could be usable. I have always assumed that they were introduced
because of a rare but important scenario in which they are
indispensable. I keep hoping that someone will come forward to counter
my arguments with just such an example, but it hasn't happened yet.

>If we follow
>that logic we should deprecate them as soon as possible.

If we can't dig up a good counter-example soon, I'm inclined to agree
with you.

>What I am
>saying is that I would love implementors to generally agree to provide a
>switch that results in them being completely ignored and having zero
>impact on code.

Do you really mean *zero impact*, or would you be willing to allow the
compiler to continue to optimize away tables in the case of throw()? I
think people might like to have both options.

>That would ensure that the runtime breach and terminate
>were avoided in production code while allowing their use in debugging
>environments which had static analisers.

I'm still not clear about the static analysis concept...

>>Greg Colvin may be able to argue from his experience with Java that it's more
>>annoying than useful, but from where I sit it seems like a good option to
>>have.
>
>I agree.  I think Greg is suffering from naive code that does not have a
>well thought out policy for using exceptions specifications.  I.e. the
>language is immature:)

Sounds like you're saying two different things. I doubt Greg's code is
naive W.R.T. exceptions. There is no doubt that the language is
immature, though.

-Dave



      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Richard Browne <richb@pobox.com.au>
Date: 1998/09/25
Raw View
Surely exception specifications can be used so that the compiler can produce a
warning in the following scenario:

void func1() throw()
{
    func2();
}

void func2() throw(std::bad_alloc)
{
    ...
}

Sure there are cases where we know for a given invocation of func2
std::bad_alloc won't be thrown because [insert some reason here]. In my
experience, these cases are rare and I'm happy to live with it. The
advantages for me of knowing that no exception is going to slip by is
enourmous.

In fact, without exception specifications I see exceptions as a black art
in which you never really know if all the cases are covered. I vote for
them whole heartedly.

Ok... now, let the flames begin....



      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: obricker@my-dejanews.com
Date: 1998/09/27
Raw View
In article <36079720.1D66C336@physik.tu-muenchen.de>,
  Christopher Eltschka <celtschk@physik.tu-muenchen.de> wrote:
> obricker@my-dejanews.com wrote:
>
> [...]
>
> > Yes, I like that. What I would really like though is a compiler that would
> > warn of uncaught exceptions at compile time. So that if a member function
> > throws a MyBaseClassException and I have no catch where its called them the
> > calling function must also throw it or I get a warning (Java just won't
> > compile it that way which I think is too radical to accept for now).
>
> What exception specification would you want for std::copy?
>
> Possibilities:
>
> - throw()
>   This causes every exception thrown from your objects to be fatal.
>
This doesn't feel right.

> - throw(...) (or no exception spec)
>   This works now, but would generate warnings if used in *any*
>   function which has a narrower throw spec (although the code
>   may just copy ints, and no exception can occur anyway), if
>   used with your warning option.
>

If the template is producing code which could have an exception thrown, I
would want the warning since I would have no other clue that it could
happen(unless I back track the many template functions and files the compiler
is using to produce std::copy())

> - throw(std::exception)
>   What if your class throws a different exception?
>
> - throw(what?)
>
> The same problem arises for about every template function.
>

I aggree that templates and exceptions specifications are in general at odds
with one another.

> Another example:
>
> MyFloat sqrt(MyFloat const&) throw(IllegalArgument);
>                      // throws if argument is negative
>
> MyFloat f() throw(); // returns only positive MyFloats
>

> void g() throw()
> {
>   cout << sqrt(f()) << endl;
> }
>
> This will generate a warning, although we know that in no case the
> exception will be thrown - but your compiler doesn't know that.
> ---

Exceptions are intended ( at least in my mind) to handle exceptional
circumstances. A failure in the f() algorithm which returns a negative number
I would find exceptional. Nothing in its return type guarantees a positive
value. If I wanted that promise then maybe:

MyPosFloat sqrt(MyPosFloat const &)throw();
MyPosFloat f() throw();
MyPosFloat MyFloat::operator MyPosFloat() throw(IllegalArgument);

Or just recogize the warning as valid but not relevent.

Since exception specs are not required and have such horrible consequences
when violated, if I am bothering with them at all its for the documentaion
value. That being the case, I would like the compiler to be able to warn me
if I am ignoring my own warnings since that is what the spec is, a warning
about what might be expected to happen.

Otis B.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/27
Raw View
In article <360abb82.1747313575@news.motu.com>, David Abrahams
<abrahams@spam.motu.com> writes
>Sounds like you're saying two different things. I doubt Greg's code is
>naive W.R.T. exceptions. There is no doubt that the language is
>immature, though.

No, I did not intend to impute that Greg's code would be naive wrt
exceptions, but he is building on top of code provided by others.

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: obricker@my-dejanews.com
Date: 1998/09/27
Raw View
In article <6u801d$dcg$1@nnrp1.dejanews.com>,
  agriffiths@ma.ccngroup.com wrote:
>
> In article <$NdKfQAziOA2EwHa@robinton.demon.co.uk>,
>   Francis Glassborow <francis@robinton.demon.co.uk> wrote:
> > Now the problem is persuading the majority that they should provide
> > exception specs (it is so easy not to).
>
> "Common sense" does indeed suggest that exception specs should be the norm.
> However, this approach causes problems:
>
> 1/
> It leads to "unexpected & terminate" being invoked at runtime when exceptional
> problems occur - and a graceless exit from your application.  In many systems
> this is undesirable.
>

This is a problem because the spec defines runtime behavior. I think I would
prefer it was only a compile time issue of checking that functions with
exception specs were called and defined in a consistant manner

> 2/ It is difficult to maintain exception specifications during the lifetime
> of the project.
>

I tend to think of this as a form of documentation/contract. Its not that big
a deal in Java. It can be a bother but it has the advantage of your knowing
what you can expect.

> 3/
> It greatly complicates the writing of templates.
>

That one I have no answer for. Except possibly limiting what exceptins certain
class operations are allowed to throw. No, I am not advocating this solution.

> The above points derive from my experience, the Taligent guidelines and from
> communication on usenet.
>
> In practice, I have found that most functions should _not_ provide a throw
> specification and that the majority of those that do should provide an empty
> one.
>

I want a way to know what exceptions a function might throw. How else am I to
know what to look for to catch and recover from?

> I can envisage exceptions: for example a stable API might helpfully provide
> more discriminating exception specs, but I've yet to see it in practice.
>
Oh, that would be nice to have.

I wonder, if the specs are such an evil thing, why did the committee add them
to the language? What use did they see for them?

Otis

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: David Bruce <dib@dera.gov.uk>
Date: 1998/09/27
Raw View
Francis Glassborow wrote:

> Curiously, I was one of those (within the UK) who wanted them removed
> (not included) in the language because I believed they were not able to
> provide any real benefit:)
>
> As regards templates, there are serious problems and with the growth of
> generic programming I think we must either seriously consider throwing
> out exception specifications or we must examine ways in which they can
> be supported in templates (I need to be able to place some sort of
> exception spec on a class template that can be provided at the
> instantiation point.  Perhaps we should also consider exception specs
> for a whole class.
>
> Please note that I am speculating here. And so ideas are good but
> screaming at me isn't (I hope)

As I see it, there are three problems with exception specifications as presently
defined in C++; unlike some of the other posters to this thread, however, I
consider them repairable (see below) and -- once repaired -- extremely valuable.



First, as others have noted, they are dangerous because they are not properly
enforced -- at compile-time -- by the compiler, and so we have the spectre of
terminate(), etc.  If they were treated like const in this respect, one could
actually rely on them; if someone whose code we used changed an exception
specification, we might have to change our own code in response, but at least we
would know about it before it's too late.


Second, and most fundamental, is that templates are incapable of making the use
of exception specifications fully generic.  Moreover, this has implications even
for non-templated code.  (In particular, it means that we cannot insulate
ourself from others changing exception specifications in a way that doesn't
matter to us.)  Consider the following function:


    int twice(int (*f)(int), int x)
    { return f(f(x)); }

It is obvious that twice can only throw an exception if f does, so we should be
able to capture this by writing something like:


    template <class X>
    int twice(int (*f)(int) throw(X), int x) throw(X)
    { return f(f(x)); }

But this templated twice is not as useful as it should be: it can only be
applied to functions that have an exception specification listing exactly one
class.  In particular, it cannot be applied to a function with empty exception
specification throw(), nor one with specification throw(...) (or no
specification at all).  Nor can it be applied to functions capable of throwing
several different classes of exception, unless perhaps they have a single common
ancestor that could be inferred (but then we lose much of the information about
which exception could be thrown).

What is required here, but I believe templates (as currently formulated) to be
incapable of supporting, is to make the function generic over a *list* (or set)
of zero or more classes; this is as much a *syntactic* limitation as anything
else.  (Note that we would also need syntax for adding and subtracting
classes/lists of classes from the list; the former to allow for several sources
of exception, the latter to recognize the effect of exception handling.)  (If
the idea of general "classlist" template parameters is considered too ambitious,
go for exceptions only with "exnspec" instead.)  Twice could then be written as:



    template <exnspec Exns>
    int twice(int (*f)(int) throw(Exns), int x) throw(Exns) { return f(f(x)); }

and a more involved example might look like:


    class NegativeArg {};

    template <exnspec Exns>
    int nonneg(int (*f)(int) throw(Exns), int x) throw((Exns + NegativeArg) - BadArg)
    {
        try {
            if (x < 0) { return f(x); } else { throw NegativeArg(); }
        }
      catch (BadArg) { ... }
    }

This should suffice for (templated) library classes (e.g., containers) too, at
least with member templates.

I don't think the implications for implementating this functionality are all
that bad; certainly I would guess that the way template expansion works in C++
should, if anything, make it easier than in the research languages (such as FX,
APOSTLE) that have dealt with polymorphic effects (a further generalization) on
similar lines.


Third, there's the question of what the default specification should be.  I
don't see why it couldn't be throw() (or perhaps throw(std::bad_alloc), since
dynamic memory is so pervasive), as long as the specifications are enforced.  We
can see what exceptions we can cause directly and, with the above formalism, can
insulate ourselves from those coming from functions we are given to call, so
that approach is feasible.  OTOH, I can see the arguments for
backwards-compatibility looming already ..., and with proper enforcement, I'll
concede that throw(...) is more tenable than it is now.  I'd be happy to settle
for a compiler flag to switch between the two positions.


So, to the C++ gurus out there, is there any reason something like the above
couldn't be made to work?  What problems remain?

(And to the implementors, when can we expect to see it in your products? :-)



Sincerely,

    David Bruce

PS.  Francis: I'm not sure I follow what you're trying to get at with your whole
class exception spec.  Could you clarify this, or give an example?

________________________________________________________________________
post: DERA Malvern, St Andrews Road, Malvern, WORCS WR14 3PS, ENGLAND
mailto:dib@dera.gov.uk ** phone: +44 1684 895112 ** fax: +44 1684 894389
[The views expressed above are entirely those of the writer and do not represent the views, policy or understanding of any other person or official body.]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/27
Raw View
In article <6ueb6g$2lf$1@nnrp1.dejanews.com>, obricker@my-dejanews.com
writes
>Since exception specs are not required and have such horrible consequences
>when violated, if I am bothering with them at all its for the documentaion
>value. That being the case, I would like the compiler to be able to warn me
>if I am ignoring my own warnings since that is what the spec is, a warning
>about what might be expected to happen.

And this is why the concept of simply using comments fails.  Exception
specs should be a compile time tool.  At runtime we have other
possibilities (after all if the exception is never caught the program
will abort anyway, but I should be able to provide a catch(...) firewall
to prevent that in critical applications.

It seems to me that we need compiler implementers to provide an
extension that makes ES compile time only (and work hard to provide real
value at this level)

We also need to do some work on how to meld ES and templates to get some
benefit here.


Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: Michael Ball <michael.ball@Eng.UCAR.EDU>
Date: 1998/09/28
Raw View
Francis Glassborow wrote:

> The argument on the other side at that time was that they would be
> useful as tools became available to do static analysis based on them.
> What you are saying is that what we have now is unusable.  If we follow
> that logic we should deprecate them as soon as possible.  What I am
> saying is that I would love implementors to generally agree to provide a
> switch that results in them being completely ignored and having zero
> impact on code.  That would ensure that the runtime breach and terminate
> were avoided in production code while allowing their use in debugging
> environments which had static analisers.

Though I tend to agree that exception specifications are relatively
useless
as defined, I think the jury is still out on how useful they are when
checked at compile time.  We had a project at Sun that used them
religiously
and swore by them.

None the less, I have to wonder about the wisdom of turning off the
checks.  They do represent preconditions of a sort, and not honoring
them could cause mysterious problems.

If you are concerned about runtime costs, the costs are in fact minimal.
In the Sun implementation, which is typical of range-table
implementations, the code is entirely in tables which are never even
swapped in unless an exception is concerned.  Implementations that have
a significant cost when the exception is not thrown should simply be
laughed out of existence.

If you are concerned about terminating your program as the result of an
unexpected exception, I think that is more defensible.  However, you
could make sure that all exception specifications contain
"std::bad_exception" and substitute an unexpected handler that rethrows.
This might not be an unreasonable "production" compiler option.  If you
do this, you will at least get reproducable results that are the same
in either mode.

-Mike-

Sun MicroSystems
Development Environments and Tools


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: "Adam P. Jenkins" <ajenkins@javanet.com>
Date: 1998/09/28
Raw View
David Abrahams wrote in message <360abb82.1747313575@news.motu.com>...
>>That would ensure that the runtime breach and terminate
>>were avoided in production code while allowing their use in debugging
>>environments which had static analisers.
>
>I'm still not clear about the static analysis concept...

Are you familiar with Java?  I won't go into an explanation of Java
exception specifications because you can read about it in any Java book,
except to say that exception specifications are enforced at compile
time.
It's therefore easy to envision a static analysis tool, or even a
compiler
switch, that did the same kind of static analysis on C++ code.  Without
static analysis, I agree with David Abrahams that C++ exception
specifications are quite useless.

--
Adam P. Jenkins
ajenkins@javanet.com





      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]





Author: Pete Becker <petebecker@acm.org>
Date: 1998/09/28
Raw View
obricker@my-dejanews.com wrote:
>
> > In practice, I have found that most functions should _not_ provide a throw
> > specification and that the majority of those that do should provide an empty
> > one.
> >
>
> I want a way to know what exceptions a function might throw. How else am I to
> know what to look for to catch and recover from?

By reading the documentation. Even with mandatory exception
specifications you have to do this: knowing that a function throws a
particular exception does not tell you under what circumstances that
exception can be thrown, so you must read the documentation in order to
understand how to respond to that exception.

--
Pete Becker
Dinkumware, Ltd.
http://www.dinkumware.com
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/22
Raw View
In article <6u60um$9jk$1@nnrp1.dejanews.com>, abrahams@motu.com writes
>I disagree with Mr. Glassborow's recommendation in the strongest terms. In
>fact, there is an excellent argument that exception-specifications have no
>place at all in production code (I didn't invent that - it came from
>Taligent's excellent guide to programming). The problem is that the run-time
>effects of an exception specification are almost never what you wanted
>(usually immediate termination), and in complex systems it is almost
>impossible to maintain exception specifications so that they are always
>up-to-date. For example, imagine a function f():


I certainly respect your opinion but it serves to make clear a serious
issue that, I believe, can only currently be resolved by implementors.
I know of no way to write code that will meet the needs of the 'no
exception specification' school and also work with those wanting them.
We cannot eve produce a hack with the preprocessor (not valid in C++,
but I have seen someone remove all uses of const from C code with
#define const

(doesn't work in C++ for several reasons)

What is needed (to meet both schools of style) is a compiler switch that
suppresses the effects of exception specifications.

I suspect that as programmers become more used to ES they will come to
use them (just as many more C programmers use const as a result of
exposure to const in C++, those exposed to ES in Java may eventually
decide they like it -- of course they might not).

In general application programmers (component assemblers) can ignore ES
if they wish.  The big impact is on those deriving from base classes and
those using templates.

Once upon a time C production code religiously compiled with #define
NDEBUG to suppress uses of assert.  This is no longer uniformly the case
as some programmers have decided that leaving the asserts in production
code meets some safety critierion.  I would be happy to see a #define
NO_ES available.  I would be even happier if this became portable.

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Christopher Eltschka <celtschk@physik.tu-muenchen.de>
Date: 1998/09/22
Raw View
obricker@my-dejanews.com wrote:

[...]

> Yes, I like that. What I would really like though is a compiler that would
> warn of uncaught exceptions at compile time. So that if a member function
> throws a MyBaseClassException and I have no catch where its called them the
> calling function must also throw it or I get a warning (Java just won't
> compile it that way which I think is too radical to accept for now).

What exception specification would you want for std::copy?

Possibilities:

- throw()
  This causes every exception thrown from your objects to be fatal.

- throw(...) (or no exception spec)
  This works now, but would generate warnings if used in *any*
  function which has a narrower throw spec (although the code
  may just copy ints, and no exception can occur anyway), if
  used with your warning option.

- throw(std::exception)
  What if your class throws a different exception?

- throw(what?)

The same problem arises for about every template function.

Another example:

MyFloat sqrt(MyFloat const&) throw(IllegalArgument);
                     // throws if argument is negative

MyFloat f() throw(); // returns only positive MyFloats

void g() throw()
{
  cout << sqrt(f()) << endl;
}

This will generate a warning, although we know that in no case the
exception will be thrown - but your compiler doesn't know that.
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: agriffiths@ma.ccngroup.com
Date: 1998/09/23
Raw View
In article <$NdKfQAziOA2EwHa@robinton.demon.co.uk>,
  Francis Glassborow <francis@robinton.demon.co.uk> wrote:
> Now the problem is persuading the majority that they should provide
> exception specs (it is so easy not to).

"Common sense" does indeed suggest that exception specs should be the norm.
However, this approach causes problems:

1/
It leads to "unexpected & terminate" being invoked at runtime when exceptional
problems occur - and a graceless exit from your application.  In many systems
this is undesirable.

2/ It is difficult to maintain exception specifications during the lifetime
of the project.

3/
It greatly complicates the writing of templates.

The above points derive from my experience, the Taligent guidelines and from
communication on usenet.

In practice, I have found that most functions should _not_ provide a throw
specification and that the majority of those that do should provide an empty
one.

I can envisage exceptions: for example a stable API might helpfully provide
more discriminating exception specs, but I've yet to see it in practice.

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "Paul D. DeRocco" <pderocco@ix.netcom.com>
Date: 1998/09/17
Raw View
Paresh Adhia wrote:

> In C++ declarations like,

> int foo2() throw();  // can not throw any exception

> gurantees that foo2() doesn't throw any exceptions, but
> following declaration allows any exception to be thrown out of
> function.

> int foo();  // can throw any exception

> I am curious as to why this approach was selected. To me, this is as
> bad as old C style function declaration of functions without
> specifying parameters. For a moment I thought this must be the
> compatability issue with legacy "C" code, but then I immediately
> realized "C" functions don't
> throw exceptions any way. Shouldn't the functions which throw any
> exceptions be defined using alternate syntax like,

> int foo() throw(...); // throws any exceptions, made explicit here

I think it mostly has to do with reverse compatibility with earlier C++,
before exceptions. There was lots of code out there that used
declarations without exception specs, and they didn't want to invalidate
it all, so they had to decide what the lack of an exception spec meant:
throw nothing or throw anything. They made the safer choice, allowing
old code to be recompiled without breaking anything.

--

Ciao,
Paul


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: "Matt Seitz" <mseitz@meridian-data.com>
Date: 1998/09/18
Raw View

Paresh Adhia wrote in message <35FEB186.361A@jpmorgan.com.com>...
>int foo2() throw();  // can not throw any exception
>int foo();  // can throw any exception
>
>I am curious as to why this approach was selected.

Dr. Stroustrup explains this in section 14.6 of THE C++ PROGRAMMING
LANGUAGE, Third Edition.



      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Francis Glassborow <francis@robinton.demon.co.uk>
Date: 1998/09/21
Raw View
In article <35FEB186.361A@jpmorgan.com.com>, Paresh Adhia <adhia_paresh@
jpmorgan.com.com> writes
>Was above (or any better) style considered by standards committee ? If
>yes, why was it not accepted ?

Yes, in considerable detail.  This is just one more example of the
default case being 180 degrees out of phase with common sense.  However
that is in no way casting aspersions on those writing the standard.

The way it as easy as possible to move between compilers that understand
exception specs and ones that do not.  It isn't so much compatibility
with legacy C but with the vast accumulation of legacy C++.

Now the problem is persuading the majority that they should provide
exception specs (it is so easy not to).  Typically I think that a member
function should be one of the following (more refined if you insist, but
at least)

throw()                // throw nothing, e.g. destructors
throw(std::exception)  // only throws exceptions rooted in the standard

                       // exception hierarchy
throw(MyBaseClassException)  // allexceptions are derived from one
                             // provided in the base class
throw(std::exception, MyBaseClassException)

Now users of your class have a fighting chance of knowing what they have
to handle.  Of course MI etc might increase the list, but generally
exceptions thrown by sub-objects should be handled locally before
throwing, if necessary, a class based exception.

Francis Glassborow      Chair of Association of C & C++ Users
64 Southfield Rd
Oxford OX4 1PA          +44(0)1865 246490
All opinions are mine and do not represent those of any organisation

      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]





Author: Jonathan Pryor <jonpryor@vt.edu>
Date: 1998/09/21
Raw View
Comments afterward...

Paresh Adhia wrote:

> In C++ declarations like,
>
> int foo2() throw();  // can not throw any exception
>
> gurantees that foo2() doesn't throw any exceptions, but
> following declaration allows any exception to be thrown out of
function.
>
> int foo();  // can throw any exception
>
> I am curious as to why this approach was selected. To me, this is as
bad
> as old C style function declaration of functions without specifying
> parameters. For a moment I thought this must be the compatability
issue
> with legacy "C" code, but then I immediately realized "C" functions
don't
> throw exceptions any way. Shouldn't the functions which throw any
> exceptions be defined using alternate syntax like,
>

You're correct in thinking it's "Legacy Code", but in this case, it's
"Legacy C++ code".  Before they had written/created/agreed upon the
syntax for declaring what exceptions a function (may) throw, a great
deal of "C++" code had been written and worked correctly on the
compilers of the time.

It was felt that if functions without a `throw' declaration implicitly
threw no exceptions, lots of code would break.  Additionally, it
would take time for this feature to make it into most of the major
compilers, during which time things could get...interesting (and
confusing).

More information about this decision can be found in
_Design and Evolution of C++, 2nd Edition_ by Stroustrup.

hth
 - Jon



      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: obricker@my-dejanews.com
Date: 1998/09/21
Raw View
In article <$NdKfQAziOA2EwHa@robinton.demon.co.uk>,
  Francis Glassborow <francis@robinton.demon.co.uk> wrote:
> In article <35FEB186.361A@jpmorgan.com.com>, Paresh Adhia <adhia_paresh@
> jpmorgan.com.com> writes
> >Was above (or any better) style considered by standards committee ? If
> >yes, why was it not accepted ?

> Yes, in considerable detail.  This is just one more example of the
> default case being 180 degrees out of phase with common sense.  However
> that is in no way casting aspersions on those writing the standard.

> The way it as easy as possible to move between compilers that understand
> exception specs and ones that do not.  It isn't so much compatibility
> with legacy C but with the vast accumulation of legacy C++.

> Now the problem is persuading the majority that they should provide
> exception specs (it is so easy not to).  Typically I think that a member
> function should be one of the following (more refined if you insist, but
> at least)

> throw()                // throw nothing, e.g. destructors
> throw(std::exception)  // only throws exceptions rooted in the standard

>                        // exception hierarchy
> throw(MyBaseClassException)  // allexceptions are derived from one
>                              // provided in the base class
> throw(std::exception, MyBaseClassException)

> Now users of your class have a fighting chance of knowing what they have
> to handle.  Of course MI etc might increase the list, but generally
> exceptions thrown by sub-objects should be handled locally before
> throwing, if necessary, a class based exception.

Yes, I like that. What I would really like though is a compiler that would
warn of uncaught exceptions at compile time. So that if a member function
throws a MyBaseClassException and I have no catch where its called them the
calling function must also throw it or I get a warning (Java just won't
compile it that way which I think is too radical to accept for now).

Otis Bricker

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum


[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: abrahams@motu.com
Date: 1998/09/22
Raw View
In article <$NdKfQAziOA2EwHa@robinton.demon.co.uk>,
  Francis Glassborow <francis@robinton.demon.co.uk> wrote:
> Now the problem is persuading the majority that they should provide
> exception specs (it is so easy not to).  Typically I think that a member
> function should be one of the following (more refined if you insist, but
> at least)
>
> throw()                // throw nothing, e.g. destructors
> throw(std::exception)  // only throws exceptions rooted in the standard
>
>                        // exception hierarchy
> throw(MyBaseClassException)  // allexceptions are derived from one
>                              // provided in the base class
> throw(std::exception, MyBaseClassException)

I disagree with Mr. Glassborow's recommendation in the strongest terms. In
fact, there is an excellent argument that exception-specifications have no
place at all in production code (I didn't invent that - it came from
Taligent's excellent guide to programming). The problem is that the run-time
effects of an exception specification are almost never what you wanted
(usually immediate termination), and in complex systems it is almost
impossible to maintain exception specifications so that they are always
up-to-date. For example, imagine a function f():

X f( const X& x, const Y& y ) throw (e1, e2)
{
  Z z = x + y;
  myStream << z;
  z.g( x );
  return z;
}

Many functions are called in the course of the execution of f(). Any one
might need to be modified during the life of a project to throw some
exception which it did not throw previously. Worse, many of these functions
are not named distinctly in the body of f(), because they are operators or
implicit conversions which could not easily be found by searching the source
code. If a f ()'s exception-specification isn't properly updated, you have a
catastrophe. But if it is updated, what is the result of your painstaking
maintenance? The answer: absolutely nothing. Exception-specifications have no
compile-time behavior. Aside from optimizations which the compiler can
potentially make, an exception-specification has no runtime behavior unless
it is violated, in which case the result is seldom useful.

Personally, I would only ever consider using an empty exception-specification
(i.e. throw() ), and then only whent the function it adorns is both trivial
enough that I have reasonable confidence that I can maintain it, and critical
enough to the execution-speed of my program that optimizing it is important.

> Now users of your class have a fighting chance of knowing what they have
> to handle.  Of course MI etc might increase the list, but generally
> exceptions thrown by sub-objects should be handled locally before
> throwing, if necessary, a class based exception.

In my experience, one very seldom needs or wants to handle different
exceptions differently. Code quickly becomes very complicated when you
constantly try to handle an out-of-memory condition differently from a disk
full error. The only places this comes up in my code are at the point of
error reporting and when there is some kind of specialized cache which can be
released in order to retry the operation. The latter is extremely rare. For
the former, you only need to write one error-reporting function, and catch
all exceptions with catch(...). The error-reporting function takes the
following general form:

void ReportCurrentException()
{
  try {
    throw; // rethrows the exception currently being handled.
  }
  catch( const e1& ) { // Handle the exceptions we know about
    // report e1 error
  }
  catch( const e2& ) {
    // report e2 error
  }
  catch( const e3& ) {
    // report e3 error
  }
    ...
  catch( ... ) { // Handle any exceptions we don't know about (just in case)
    // report unknown error
  }
}

-Dave

-----== Posted via Deja News, The Leader in Internet Discussion ==-----
http://www.dejanews.com/rg_mkgrp.xp   Create Your Own Free Member Forum
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Greg Colvin <spam@me.not>
Date: 1998/09/22
Raw View
Francis Glassborow <francis@robinton.demon.co.uk> wrote in article
<$NdKfQAziOA2EwHa@robinton.demon.co.uk>...
> In article <35FEB186.361A@jpmorgan.com.com>, Paresh Adhia <adhia_paresh@
> jpmorgan.com.com> writes
> >Was above (or any better) style considered by standards committee ? If
> >yes, why was it not accepted ?
>
> Yes, in considerable detail.  This is just one more example of the
> default case being 180 degrees out of phase with common sense.  However
> that is in no way casting aspersions on those writing the standard.

In this case, I think your "common sense" is mistaken. (And I can state
from experience that Francis' sense is usually uncommonly good.)

I'm being paid to write a lot of Java of late, where exception
specifications are enforced by the compiler, and the default is throw(),
and I don't like it at all.

Most of the time for most functions I don't care what they throw.  A
function's job is just to manage the resources it owns, if any, and pass
on any exceptions it encounters to its caller, no matter what exception
is thrown at it.  For the most part, I find the only useful specification
in C++ to be throw().

So in C++ that means I don't need many throw specifications, and can just
count on destructors to do their job, but in Java I wind up writing far
too many throws Throwable specifications and finally clauses.

I've tried using more specific specs in Java, and find that I then am
forced to keep changing them, and those of all callers, as the
implementation of a function evolves.  The effect is not unlike the
hassle of making a C++ program "const correct" for the first time, but
unlike that excercise it is ongoing and relentless.

So, whatever the historical necessity, I think throws() is the most
useful default.

Greg Colvin
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]






Author: Paresh Adhia <adhia_paresh@jpmorgan.com.com>
Date: 1998/09/17
Raw View
In C++ declarations like,

int foo2() throw();  // can not throw any exception

gurantees that foo2() doesn't throw any exceptions, but
following declaration allows any exception to be thrown out of function.

int foo();  // can throw any exception

I am curious as to why this approach was selected. To me, this is as bad
as old C style function declaration of functions without specifying
parameters. For a moment I thought this must be the compatability issue
with legacy "C" code, but then I immediately realized "C" functions don't
throw exceptions any way. Shouldn't the functions which throw any
exceptions be defined using alternate syntax like,

int foo() throw(...); // throws any exceptions, made explicit here

And functions without exception specifier should be assumed to be NOT
throwing exceptions ? Like,

int foo2(); // will not throw any exception

Was above (or any better) style considered by standards committee ? If
yes, why was it not accepted ?

Since I prefer declaration to manifest all the details about interface
and at the same time I don't want to code throw() for majority of the
functions (which will not be throwing exceptions) I write, this style
bothers me.

Thanks for sharing your knowledge

Paresh
--
Please remove extra .com from my address to reply me directly.


      [ Send an empty e-mail to c++-help@netlab.cs.rpi.edu for info ]
      [ about comp.lang.c++.moderated. First time posters: do this! ]



[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]