467,075 Members | 975 Online
Bytes | Developer Community
Ask Question

Home New Posts Topics Members FAQ

Post your question to a community of 467,075 developers. It's quick & easy.

Forcing exception handling

hi

in java i found that when a method has a throws clause in the definition,
callers must either handle the exceptions thrown by the method they are
calling or "forward" the exception to the caller by specifying a throws
clause as well.

is there a similar machanism in c++? i want to force a developer to write
handlers for all possible exceptions a method of my class library can throw.
thanks
bruno
Jul 19 '05 #1
  • viewed: 3214
Share:
12 Replies
On Fri, 25 Jul 2003 23:30:55 +0200, "Ritz, Bruno" <br********@gmx.ch> wrote:
in java i found that when a method has a throws clause in the definition,
callers must either handle the exceptions thrown by the method they are
calling or "forward" the exception to the caller by specifying a throws
clause as well.

is there a similar machanism in c++?
Nope. There are exception specifications, but the default
is a call to std::unexpected when an exception doesn't match,
and std::unexpected defaults to calling std::terminate or,
if the exception specification "lists" (very unclear language
in the standard here) std::bad_exception, throwing that. Most
experienced C++ programmers regard the empty exception
specification, and possibly but just possibly the specification
allowing std::exception, as the only useful specification(s).

i want to force a developer to write handlers for all possible
exceptions a method of my class library can throw.


You're EVIL! <g>

Could you give a concrete example of method throwing some
different exceptions, where these _must_ be handled by the
caller and in different fashions?

Jul 19 '05 #2

"Ritz, Bruno" wrote:
[...]
is there a similar machanism in c++?
Nope.
i want to force a developer to write
handlers for all possible exceptions a method of my class library can throw.


And why do you want to force anyone to do (or not do) anything? If
all you want is just to exercise some authority, well, that's what
kids are for. Do you have kids?

regards,
alexander.

P.S. Ah well,

http://groups.google.com/groups?selm...00006%40web.de
(Subject: Re: C++ exception handling)

http://groups.google.com/groups?thre...8A462%40web.de
(Subject: Re: Guru of the Week #82: Solution)
Jul 19 '05 #3

"Alf P. Steinbach" wrote:
[...]
in the standard here) std::bad_exception, throwing that. Most
experienced C++ programmers regard the empty exception
specification, and possibly but just possibly the specification
allowing std::exception, as the only useful specification(s).


Yeah. But most MOST experienced C++ programmers think that there are
serious problems with the current C++ exception handling due to lack
of mandatory *2-phase* processing and totaly busted ESes.

http://google.com/groups?threadm=3EB...E66C4%40web.de
(Subject: __attribute__((cleanup(function)) versus try/finally)

http://google.com/groups?threadm=3EC...0B266%40web.de
(Subject: Exception handling... it's time to fix the standard)

http://google.com/groups?threadm=3EE...7A32D%40web.de
(Subject: std0X::expected_exception<T>())

http://google.com/groups?threadm=ubr...consulting.com
(Subject: Re: std0X::expected_exception<T>() [repost])

regards,
alexander.
Jul 19 '05 #4
it is not about "to exercise some authority". ever had the idea that i had
the stability of the application in mind?

i just do not want uncaught exceptions.
"Alexander Terekhov" <te******@web.de> wrote in message
news:3F***************@web.de...

"Ritz, Bruno" wrote:
[...]
is there a similar machanism in c++?
Nope.
i want to force a developer to write handlers for all possible exceptions a method of my class library can

throw.
And why do you want to force anyone to do (or not do) anything? If
all you want is just to exercise some authority, well, that's what
kids are for. Do you have kids?

regards,
alexander.

P.S. Ah well,

http://groups.google.com/groups?selm...00006%40web.de
(Subject: Re: C++ exception handling)

http://groups.google.com/groups?thre...8A462%40web.de
(Subject: Re: Guru of the Week #82: Solution)

Jul 19 '05 #5
why is that a useless mechanism?

"Jonathan Mcdougall" <DE******************@yahoo.ca> wrote in message
news:at********************************@4ax.com...
in java i found that when a method has a throws clause in the definition,
callers must either handle the exceptions thrown by the method they are
calling or "forward" the exception to the caller by specifying a throws
clause as well.
Which is a completly useless mechanism.
is there a similar machanism in c++?


Of course not.
i want to force a developer to write
handlers for all possible exceptions a method of my class library can

throw.
Comments would be best.
Jonathan

Jul 19 '05 #6
On Sat, 26 Jul 2003 00:01:25 +0200, Alexander Terekhov <te******@web.de> wrote:

"Alf P. Steinbach" wrote:
[...]
in the standard here) std::bad_exception, throwing that. Most
experienced C++ programmers regard the empty exception
specification, and possibly but just possibly the specification
allowing std::exception, as the only useful specification(s).
Yeah. But


But?

most MOST experienced C++ programmers
I looketh at tree first URLs, all postings from you, my friend.

You're certainly experienced in threading issues.

I don't dispute that it might be true that most MOST experienced
C++ programmers think there are problems, and I even agree that there
are problems (although perhaps not the ones you're referring to), but
I think such appeals to vaguely defined authority, as opposed to
information about common practice, are irrelevant.

think that there are
serious problems with the current C++ exception handling due to lack
of mandatory *2-phase* processing and totaly busted ESes.

http://google.com/groups?threadm=3EB...E66C4%40web.de
(Subject: __attribute__((cleanup(function)) versus try/finally)

http://google.com/groups?threadm=3EC...0B266%40web.de
(Subject: Exception handling... it's time to fix the standard)

http://google.com/groups?threadm=3EE...7A32D%40web.de
(Subject: std0X::expected_exception<T>())

http://google.com/groups?threadm=ubr...consulting.com
(Subject: Re: std0X::expected_exception<T>() [repost])


Could you perhaps summarize your views with no _parenthetical_
examples?

A few examples with following elucidation would be nice.

Jul 19 '05 #7

"Ritz, Bruno" wrote:

it is not about "to exercise some authority". ever had the idea that i had
the stability of the application in mind?

i just do not want uncaught exceptions.


How about terrorists or natural disasters? You can't really "force"
someone to prevent them, I'm afraid.

http://article.gmane.org/gmane.comp....st.devel/22348
(Re: [boost::thread] locks, exceptions and assertions)

regards,
alexander.
Jul 19 '05 #8

"Alf P. Steinbach" wrote:

On Sat, 26 Jul 2003 00:01:25 +0200, Alexander Terekhov <te******@web.de> wrote:

"Alf P. Steinbach" wrote:
[...]
in the standard here) std::bad_exception, throwing that. Most
experienced C++ programmers regard the empty exception
specification, and possibly but just possibly the specification
allowing std::exception, as the only useful specification(s).
Yeah. But


But?


Uhmm. Better understanding things. "But",
most MOST experienced C++ programmers
I looketh at tree first URLs, all postings from you, my friend.


Really? Your local google has some problems, I guess.

[...] Could you perhaps summarize your views with no _parenthetical_
examples?
Here's a "copy&paste". Does this help?

David Butenhof wrote:
[...]
--- in C/POSIX module ---

void cleanup(void *) {
printf("hello\n");
}

void c_f() {
pthread_cleanup_push(cleanup, 0);
pthread_exit(0);
pthread_cleanup_pop(0);
}

--- in C++ 'main' module ---

struct object { ~object() { printf("hello\n"); } };

void f() throw() {
object o;
c_f();
}

int main() {
f();
}

How many times will we see "hello"?


I see it three times, because that's how many times you typed it. (Was that
a trick question? ;-) )


;-)

Seriously, though, I think that's very much the crux of your argument, isn't
it?
Yep.
I would expect "hello" to be output by the POSIX cleanup handler as
c_f() is unwound in response to pthread_exit(). THAT is clearly specified
by current standards.
NO! I can see nothing in the POSIX standard that would prohibit
the following implementation of pthread_exit():

extern "C" void pthread_exit(void * ptr) {
std::thread_exit(ptr);
}

using something along the lines of: (from the "std" namespace)

class thread_termination_request : public std::exception ...
class thread_cancel_request : public std::thread_termination_request ...
class thread_exit_request : public std::thread_termination_request ...

template<typename T>
class thread_exit_value : public std::thread_exit_request ...

template<typename T>
void thread_exit(T value) {
assert(std::thread_self().can_exit_with<T>());
throw thread_exit_value(value);
}

< as an aside: Attila, do you follow me? >

I see almost-no-problems** catching and "finalizing" ANY of these
exceptions. If one can catch-and-finalize "thread termination" and
cause an abnormal process termination right after "finalizing" it,
I don't see why this can't be done by the implementation at throw
point due to ES violation.

**) http://www.opengroup.org/austin/mail.../msg05202.html
(Subject: XSH ERN 77, 81 and 82)

Now, though, we face what may be a philosophical issue, if it's not
carefully tied down by the C++ standard (which I haven't read, much less
analyzed in detail). If C++ is required to have 2-phase exceptions AND if
It isn't required, currently.
an implementation is not allowed to SEARCH (phase 1) through f()'s empty
throw() specification, then I would expect to see std::unexpected() fire
before the second "hello" can be written by o's destructor.
NO! Before the FIRST "hello"! (I know that you know that the answer
I wanted is a sort of /pthread_/null of "hello" ;-) ). Because the
"handler" inject by pthread_cleanup_push() shall be modeled upon
a C++ destructor, not archaic try/finally.

However, you have suggested that a single phase unwind implementation is
allowed, and in such an implementation I would expect o's destructor to
run, printing a second "hello", and THEN for std::unexpected() to fire as
the runtime attempts to unwind through the empty throw() specification.
Yes. Well, please take a loot at:

http://groups.google.com/groups?selm...0B266%40web.de
(Subject: Exception handling... it's time to fix the standard)

I can tell you that the C++ implementation on both Tru64 UNIX and OpenVMS,
compiled and run with default options, print "hello" twice and THEN abort
with unexpected().
That's exactly what the C++ standard currently mandates, so to speak.
(Proving that, as I said, while OpenVMS has always
supported 2-phase exceptions and recommends cleanup on the unwind phase,
not everyone actually uses it that way. ;-) )
Yeah, unfortunately, that's seems to be true with respect to majority
of C++ committee members too.

I can also say that on Tru64 UNIX (I didn't bother going through the extra
gyrations to get and analyze a process core dump on OpenVMS), the core file
leads one to the f() frame (though there's terminate and abort and raise
and all that stuff on top of it) so that someone diagnosing the abort might
be lead to examine the f() function and notice the empty throw()
specification. (While OpenVMS reports that "terminate or unexpected" has
been invoked, on Tru64 you get only "Resources lost(coredump)".)

This at least meets my minimal requirements, that the cleanup and unwind be
properly synchronized. I'd be vexed at an implementation that maintained a
separate stack of cleanup handlers, for example, and called them without
actually unwinding the call stack, so that the final core file might show
c_f() as the active frame even though cleanup had occurred out through f().
I'd be annoyed if the core file showed NO active frames, because there'd be
no clue to what happened.
Yes.

I also understand that YOU would prefer that std::unexpected() would fire
without running ANY cleanup OR unwinding any frames as the SEARCH exception
pass (phase 1) ran up against the empty throw() specification.
YES!

I'm inclined to agree with you philosophically, but with one foot (plus a
heel of the other foot) planted firmly in the real world, I'd worry about
the consequences of breaking external invariants by suddenly adding a
requirement that ~o() not be run in this case. Even your trivial example
shows where this could cause problems, because you do have an external
invariant. The output of this program might be redirected into a file that
might be used as a benchmark for testing (or for other purposes), ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^

Oh, http://groups.google.com/groups?selm...C5B37%40web.de

#include <cassert> // The C++ stuff
#include <stdio.h> // The POSIX one
#include "errbutt" // That's my own

int main() {
int rc;
rc = printf("Hello World\n");
assert(rc);
if (rc < 0 || (rc = fclose(stdout)) == EOF) {
rc = errno;
assert(rc);
}
else {
assert(!rc);
}
return rc ? report_error(rc) : 0;
}

;-)
and the
change in output from "hello\nhello\n" to "hello\n" between one version of
the C++ runtime and another could indeed be an issue.


Yes, I understand. But please note that propagation of exceptions
(unwinding) when "no matching handler found" is implemention-defined
(well, ES aside) in the current C++ standard. Portably, folks just
can't rely on always-unwind... if they don't use catch(...) and/or
"current" version of ES. The funny thing is that exceptions specs
are considered sort-of "harmful" by many "prominent" members of the
C++ community and aren't recommended.

http://www.gotw.ca/publications/mill22.htm
http://www.boost.org/more/lib_guide....-specification

regards,
alexander.

--
http://groups.google.com/groups?selm...2F8B2%40web.de
Jul 19 '05 #9
Please, don't top post.
>in java i found that when a method has a throws clause in the definition,
>callers must either handle the exceptions thrown by the method they are
>calling or "forward" the exception to the caller by specifying a throws
>clause as well.
Which is a completly useless mechanism.
why is that a useless mechanism?


<personal opinion>

If your function throws, write it in the documentations, but let me
deal with it. If I think an exception is worth catching it (such as a
minor error), let me catch it. If not, give me a break with
compilation errors, I've got well enough with templates and typos :)

Even then, I believe exceptions are not to be thrown when minor errors
occured, but that is the way I work.

I don't think a programmer has to be *forced* to catch an exception,
such mechanisms are useless when you know what you are doing and
knowing what I do does not mean I catch every exception.

</personal opinion>
Jonathan

Jul 19 '05 #10
you are right, i cannot prevent everything, but i want to prevent exceptions
thrown within my code to cause serious application errors or crashes. if the
os fails (i mean really fails), then of course i cannot to too much.

if i force handling or "forwarding" of an exception, it is a way of "asking"
a developer "are you aware of that possible error case?"

when forcing exception handling i know everywhere in the code what errors
could occur so i can prepare the code for proper handling.
"Alexander Terekhov" <te******@web.de> wrote in message
news:3F***************@web.de...

"Ritz, Bruno" wrote:

it is not about "to exercise some authority". ever had the idea that i had the stability of the application in mind?

i just do not want uncaught exceptions.


How about terrorists or natural disasters? You can't really "force"
someone to prevent them, I'm afraid.

http://article.gmane.org/gmane.comp....st.devel/22348
(Re: [boost::thread] locks, exceptions and assertions)

regards,
alexander.

Jul 19 '05 #11
"Ritz, Bruno" <br********@gmx.ch> wrote in message
news:3f********@news.swissonline.ch...
why is that a useless mechanism?

"Jonathan Mcdougall" <DE******************@yahoo.ca> wrote in message
news:at********************************@4ax.com...
in java i found that when a method has a throws clause in the definition,callers must either handle the exceptions thrown by the method they are
calling or "forward" the exception to the caller by specifying a throws
clause as well.


Which is a completly useless mechanism.
is there a similar machanism in c++?


Of course not.
i want to force a developer to write
handlers for all possible exceptions a method of my class library can

throw.

Comments would be best.
Jonathan


IMO, the best way of doing this is enclosing _all_ your code in a try block,
followed by a catch(...) clause. This way, if the code in the catch clause
is reached, you will know for sure that you have an unhandled exception.
E.g.:

#include <iostream>
#include "whatever.h"

#define UnhandledExceptionHandler() UnhandledExceptionHandler(__FILE__,
__LINE__)
void UnhandledExceptionHandler(const char* c, int n)
{
std::cout << "Unhandled eexception in file " << c << " on line " << n <<
'\n';
}
in your code do this:
void function()
{
try
{
//everything
}
catch (MyException1 e)
{
//handle it
}
catch (MyException2 e)
{
//handle it
}
// and so on
catch (...)
{
UnhandledExceptionHandler();
}
}
HTH,
S. Armondi
Jul 19 '05 #12

Samuele Armondi wrote:
[...]
IMO, the best way of doing this is enclosing _all_ your code in a try block,
followed by a catch(...) clause.


You've been reading way too much Sutter, I guess.

http://article.gmane.org/gmane.comp....st.devel/20858
(Re: Exception handling... it's time to fix the
http://www.boost.org/more/error_handling.html)

regards,
alexander.
Jul 19 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by adi@message4u.com | last post: by
3 posts views Thread by Master of C++ | last post: by
2 posts views Thread by tom | last post: by
9 posts views Thread by C# Learner | last post: by
44 posts views Thread by craig | last post: by
2 posts views Thread by Steve | last post: by
1 post views Thread by George2 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.