Re: c++-Exception-Handling when using the jpeglib
On 2007-09-24 13:33:41 -0400, Thomas Richter <thor@math.tu-berlin.de> said:
f.laszlo@pilz.de wrote:
I use the (C-written) jpeglib and I want to provide my own error
handler, implemented with try/catch. I don't have any idea why it
doesn't work. After I read the documentation of the library, lngjmp
and setjmp are proposed to handle errors properly. MSDN says: "DO not
use setjmp/lngjmp" within c++-applications.
...unless you know what you're doing. The problem with setjmp/longjmp
is that they do not clean up objects (they don't call destructors) of
all the objects on the stack.
Except when they do. <g> Technically, if replacing setjmp and longjmp
with catch and throw would destroy any auto objects, the behavior of
setjmp/longjmp is undefined. Some implementations do destroy auto
objects.
However, since the library is a C library
in first place, there are no destructors to be called in first place.
So I tried the following:
- Wrote a class with a static function "static void ErrorHandler"
which throws an Error-code whenever something goes wrong within the
jpeglib.
This causes undefined behaivour. You try to "throw an error thru C
code", which is likely to fail. The problem is that throwing an
exception requires the compiler to generate code for cleaning up objects
on the stack traceback to the corresponding catch-call, and this data
is often statically generated for each function and then searched on
while the exception is processed. Obviously, no such data has been
generated for the C library, so the compiler would not know what to do
with the exception.
Sure it does: it skips stack frames that don't have any unwind
information. That's the right thing to do, since there's nothing to be
destroyed in the C code. As you say, the behavior is undefined, but
compiler writers generally try to make this work.
I have no qualms about throwing exceptions through C code. I'd be much
more worried about using longjmp in C++ code -- whatever it does is not
portable, but if the compiler documents what it does and that's what
you need, then it should work just fine.
--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]