473,748 Members | 8,367 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
12 3689
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_except ion, 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_except ion, 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(functio n)) 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.d e> 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.c om...
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.d e> wrote:

"Alf P. Steinbach" wrote:
[...]
in the standard here) std::bad_except ion, 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(functio n)) 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.d e> wrote:

"Alf P. Steinbach" wrote:
[...]
in the standard here) std::bad_except ion, 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(vo id * ptr) {
std::thread_exi t(ptr);
}

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

class thread_terminat ion_request : public std::exception ...
class thread_cancel_r equest : public std::thread_ter mination_reques t ...
class thread_exit_req uest : public std::thread_ter mination_reques t ...

template<typena me T>
class thread_exit_val ue : public std::thread_exi t_request ...

template<typena me T>
void thread_exit(T value) {
assert(std::thr ead_self().can_ exit_with<T>()) ;
throw thread_exit_val ue(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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2883
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses return code (not generating error/exception) so it is more compatible with other programming language.
7
6006
by: Noor | last post by:
please tell the technique of centralize exception handling without try catch blocks in c#.
3
2750
by: Master of C++ | last post by:
Hi, I am an absolute newbie to Exception Handling, and I am trying to retrofit exception handling to a LOT of C++ code that I've written earlier. I am just looking for a bare-bones, low-tech exception handling mechanism which will allow me to pass character information about an error and its location from lower-level classes. Can you please critique the following exception handling mechanism in terms of my requirements ?
2
2595
by: tom | last post by:
Hi, I am developing a WinForm application and I am looking for a guide on where to place Exception Handling. My application is designed into three tiers UI, Business Objects, and Data Access Layer. My questions is where should I put exception handling: 1) Should it be put in all significant methods in all layers? 2) Should I create an exception base class that will handle the errors and pass useful error messages to the user?
9
2538
by: C# Learner | last post by:
Some time ago, I remember reading a discussion about the strengths and weaknesses of exception handling. One of the weaknesses that was put forward was that exception handling is inefficient (in the way of CPU usage), compared to the "normal" practise returning values. How true is this? Will using using exception handling, in general, be much less efficient than returning values, or less efficient at all? Just curious...
44
4224
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level user tasks should always be included in a try/catch block that actually handles any exceptions that occur (log the exception, display a message box, etc.). 2. Low-level operations that are used to carry out the high level tasks
7
6167
by: Mark Rae | last post by:
Hi, I wrote a Windows service for a client a few months ago, and the client has now asked me to modify it so that it shuts itself down under certain circumstances e.g. a catastrophic failure of the network, SQL Server connectivity problems etc. I've tried to explain that this probably isn't a very good idea nor is it even necessary because the service has sufficient error and exception handling code to take account of such situations...
2
1027
by: Steve | last post by:
Hi, Is their any way to setup VS such that it forces programmers to handle all exception (similar to Java). Thanks --
1
3109
by: George2 | last post by:
Hello everyone, Such code segment is used to check whether function call or exception- handling mechanism runs out of memory first (written by Bjarne), void perverted() { try{
0
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9238
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4593
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.