473,837 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Implementing exceptions of C++ in C

Hi All,

I am not sure if I should be asking this question on clc or clc++. Let me try on
both. I hope that this is not too trivial for the brilliant minds over here.
I know that OOP questions have been asked on clc before so it is probably OK.

I am a newbie to C++. BS 3rd edition states:

% The throw transfers control to a handler for exceptions ....
%
% ... the implementation will unwind the function call stack as needed to get
% back to the context of that caller. Thus throw acts as a multilevel return.

My mind is so C-ish that I totally fail to comprehend what is going on.
My dumb brain has these pre-reqs. Explain the usage and idea of

throw
exception
try
catch

with a C++ code and a parallel code in C. If it must involve goto's, go ahead.
But the translation must be as highly parallel as possible. Furthermore, if
you have some way to depict this, and supplement by "function call stack"
diagrams, all the better.

Thanks++,

--

,--. Bernard Klein, Berlin, Germany ,= ,-_-. =.
/ ,- ) ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. \_/

Jul 22 '05 #1
9 2671
Ian
Bernard wrote:
Hi All,

I am not sure if I should be asking this question on clc or clc++. Let me try on
both. I hope that this is not too trivial for the brilliant minds over here.
I know that OOP questions have been asked on clc before so it is probably OK.

I am a newbie to C++. BS 3rd edition states:

% The throw transfers control to a handler for exceptions ....
%
% ... the implementation will unwind the function call stack as needed to get
% back to the context of that caller. Thus throw acts as a multilevel return.

My mind is so C-ish that I totally fail to comprehend what is going on.
My dumb brain has these pre-reqs. Explain the usage and idea of

throw
exception
try
catch

with a C++ code and a parallel code in C. If it must involve goto's, go ahead.
But the translation must be as highly parallel as possible. Furthermore, if
you have some way to depict this, and supplement by "function call stack"
diagrams, all the better.

I don't think there is a clean way of replicating this in C. Otherwise
we'd all be doing it! It requires run time support in C++, so you can't
make a stand alone C++ app with exceptions, you have to link a run time.

Also C doen't create "Objects" in the C++ sense (no concept of a
destructor), so you can't destroy them as the stack is unwound.

Ian
Jul 22 '05 #2

"Ian" <no***@nowhere. com> wrote in message

I don't think there is a clean way of replicating this in C. Otherwise
we'd all be doing it! It requires run time support in C++, so you
can't make a stand alone C++ app with exceptions, you have to
link a run time.
That might be true on your platform, because exceptions require a lot of
extra code which might be in a library somewhere. However there is no
inherent reason why C++ program including exceptions can't be standalone
exectutables.
Also C doen't create "Objects" in the C++ sense (no concept of a
destructor), so you can't destroy them as the stack is unwound.

This is the problem. It is extremely difficult to implement exception
handling in C, certainly in any form that is human-usable.
Jul 22 '05 #3
On 2004-04-17, Bernard <ob**********@e lsewhere.net> wrote:
I am a newbie to C++. BS 3rd edition states:

% The throw transfers control to a handler for exceptions ....
%
% ... the implementation will unwind the function call stack as needed to get
% back to the context of that caller. Thus throw acts as a multilevel return.

My mind is so C-ish that I totally fail to comprehend what is going on.
Consider setjmp() and longjmp() from <setjmp.h>. The analogs are not
perfect, but longjmp() acts as a multilevel return.
My dumb brain has these pre-reqs. Explain the usage and idea of

throw
exception
try
catch

with a C++ code and a parallel code in C.


See: http://www.nicemice.net/cexcept/

-- James
Jul 22 '05 #4
Thus far, all replies are useful but let me explain ...

OK, if you cannot write translation of the C++ code in parallel
C for whatever reason - that I will try to understand later - can
you explain program flow. This is what is not clear to me. If you
put some verrry simple C++ code (for learning syntax) and words
or flowchart to explain
program flow. I mean C books have those railroad diagrams for
trivial things like sequence-selection-iteration-continue-break
etc. Can we see a clear program flow for this statement? As well
as a note to describe the side-effects of this stack?

You gotta make lucid what is not. Not make lucid what already is
simple, like sequence-selection-iteration-continue-break.

I totally fail to comprehend what is going on. Explain the usage and idea of

throw
exception
try
catch

with a C++ code and arrows or words to show program flow.

From: http://www.nicemice.net/cexcept/

\begin{quotatio n}

cexcept
Cosmin Truta and I have developed a try/catch/throw exception-handling interface for C. It basically works the way you would expect:

Try {
/* Maybe a Throw statement will be executed */
/* (maybe within a deeply nested function): */
/* Throw e; */
/* If so, execution jumps to the catch clause. */
}
Catch (e) {
/* An exception was thrown and copied into e. */
}

The interface of the latest release is fully implemented and documented in cexcept.h.

\end{quotation}

does have try-catch but not throw syntax. I want to first absorb the
syntax and then its semantic meaning in terms of program flow. C code,
requested in original post, was just a language that I knew well.

Thanks++,

--

,--. Bernard Klein, Berlin, Germany ,= ,-_-. =.
/ ,- ) ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. \_/

Jul 22 '05 #5
On Sat, 17 Apr 2004 07:27:40 PST in comp.lang.c++,
ob**********@el sewhere.net (Bernard) wrote,
Thus far, all replies are useful but let me explain ...

OK, if you cannot write translation of the C++ code in parallel
C for whatever reason - that I will try to understand later - can
you explain program flow. This is what is not clear to me. If you
put some verrry simple C++ code (for learning syntax) and words
or flowchart to explain


Nobody can explain it to you as long as you crosspost between
comp.lang.c and comp.lang.c++, because any correct answer is
going to be off-topic in at least one of those groups.

Jul 22 '05 #6

Bernard wrote:
Thus far, all replies are useful but let me explain ...

OK, if you cannot write translation of the C++ code in parallel
C for whatever reason - that I will try to understand later - can
you explain program flow. This is what is not clear to me. If you


int foo1()
{
int bar = 1;
throw bar;
return 2;
}

int foo2()
{
float bar = 1.0f;
throw bar;
return 2;
}

int main()
{
int result = EXIT_FAILURE;

try
{
foo1();
foo2();
result = EXIT_SUCCESS;
}
catch(int x)
{
printf("int exception caught: %d", x);
}
catch(...)
{
printf("unknown exception caught");
}

return result;
}

OK, it works like this. main() starts as usual, and executes as usual up
until it hits the "try". At that point, the compiler has noted that any
exceptions thrown inside that block are handled by one of the handlers
immediately following it. Then execution continues.

When it gets to foo1(), foo1() throws an exception of type int.
Immediately normal execution stops, and the program starts looking for
the exception handler that will be responsible for handling the int
exception. There is no "try" block in foo1(), so it just leaves it
(cleaning up anything that needs to be cleaned up along the way) without
executing the return statement and climbs back up the call stack up a
step. Then it's in main(), and main *does* contain a "try" block. So it
checks the handlers ("catch" statements) at the end of the try block to
see if any matches. Note, it does NOT call foo2() or the next statement,
it goes immediately to the handler.

Because there is a handler for int, it goes there, and inside the
exception, it prints "int exception caught: 1" (I hope, I don't use
printf anymore). Once it gets to the end of the catch block, it skips to
the end of all the exception handlers, and executes the return statement.

So linearly, this is what happened:

main starts:
main: int result = EXIT_FAILURE;
main: foo1();
foo1 starts:
foo1: int bar = 1;
foo1: throw bar;
int exception thrown (value: 1), immediately leaves foo1
jumps to int exception handler
main: sets x = 1 (from the exception)
main: printf("int exception caught: %d", x);
finished exception handler
main: return result;
main ends:

Now if you comment out the throw statement in foo1, you get this instead:

main starts:
main: int result = EXIT_FAILURE;
main: foo1();
foo1 starts:
foo1: int bar = 1;
foo1: return 2;
foo1 ends:
foo2 starts:
int exception thrown (value: 1), immediately leaves foo2
looks for float exception handler, can't find it, sees a "catch-all"
handler, jumps there
main: printf("int exception caught: %d", x);
finished exception handler
main: return result;
main ends:

The mechanics of it are pretty complex, and that without nesting try
blocks or other complexities. It's probably better to think of
exceptions in terms of what they are there for. Consider the following
example:

vector3d shrink_vector(v ector3d v, int scale_factor)
{
v.x /= scale_factor;
v.y /= scale_factor;
v.z /= scale_factor;
return v;
}

vector3d make_unit_vecto r(vector3d v)
{
// calculates vector's length. not important, so not included
int length = get_vector_leng th(v);
return shrink_vector(v , length);
}

void high_level_func tion()
{
vector3d v = get_vector_some how();
vector3d u = make_unit_vecto r();

printf("Your unit vector is: (%d, %d, %d)", u.x, u.y, u.z);
}

Now, take a look at shrink_vector() . What if the scale_factor is 0? You
can't divide by zero, that would be a disaster. But what on earth is
shrink_vector() supposed to do if you send it a 0? Should it silently
convert it to 1? No, that makes no sense. Return vector (0, 0, 0)? No,
that also makes no sense, mathematically. It could call some kind of
error function, but which one? You won't be able to reuse the function
easily if you have to use it with the same error function.

Clearly, the best think for shrink_vector to do is pass the buck. After
all, it wasn't responsible for the 0 and it couldn't fix it. So rewrite
it as:

vector3d shrink_vector(v ector3d v, int scale_factor)
{
if (scale_factor == 0)
{
divide_by_zero_ exception dbz;
throw dbz;
}

v.x /= scale_factor;
v.y /= scale_factor;
v.z /= scale_factor;
return v;
}

Now, what about make_unit_vecto r()? It would know if it was trying to
make a zero-vector a unit vector after it finds the length, but what
should it do about it? Again, you *could* put the error handling in
there, but that would limit the reuse. So, do nothing.

Now, high_level_func tion should know what to do if there is a problem.
So rewrite it like this:

void high_level_func tion()
{
try
{
vector3d v = get_vector_some how();
vector3d u = make_unit_vecto r();

printf("Your unit vector is: (%d, %d, %d)", u.x, u.y, u.z);
}
catch (divide_by_zero _exception x)
{
printf("You entered a zero vector.");
}
// NOTE: any exceptions that high_level_func tion does
// not need to know how to handle, get passed up to whoever
// called it (eg. an out of memory exception)
}

So all the exception handling is in one place, and that's in a high
level function that knows what to do about it. As your program gets
smarter, it scales nicely. For example, suppose that in the
get_vector_leng th() function, calculating the length turns out to cause
integer overflow. No problem, just throw an integer_overflo w_exception
there, and add a catch block in high_level_func tion to handle it.

I have tried to keep the examples as C-like as possible, but obviously,
this is a C++ phenomenon. That opens up a whole new world of
constructors and destructors, and the possiblity of using polymorphic
objects as exception types (in the example above, both
divide_by_zero_ exception and integer_overflo w_exception could derive
from math_exception, then you would only need to catch that, unless you
were interested in the specifics), among other things. Some aspects of
exception handling can be mimed in C, but since C is not polymorphic
object aware and does not know about destructors, there would be a
forbidding amount of work to get the full power without introducing a
whole whack of bugs (and by that I mean work not only on the side of the
guy making them, I mean also work by the guy trying to use them).

mark

Jul 22 '05 #7

"Bernard" <ob**********@e lsewhere.net> a écrit dans le message de
news:d5******** *****@ID-300100.news.uni-berlin.de...
Hi All,
Hi,

I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions have been asked on clc before so it is probably OK.
I am a newbie to C++. BS 3rd edition states:

% The throw transfers control to a handler for exceptions ....
%
% ... the implementation will unwind the function call stack as needed to get % back to the context of that caller. Thus throw acts as a multilevel return.
My mind is so C-ish that I totally fail to comprehend what is going on.
My dumb brain has these pre-reqs. Explain the usage and idea of

throw
exception
try
catch

with a C++ code and a parallel code in C. If it must involve goto's, go ahead. But the translation must be as highly parallel as possible. Furthermore, if you have some way to depict this, and supplement by "function call stack"
diagrams, all the better.
Laurent Deniau provides a basic but very nice implementation in C of
C++-style exceptions with his library OOPC (Object Oriented Programming in
C). It's well documented and easy to use.

http://ldeniau.home.cern.ch/ldeniau/html/oopc/oopc.html

Regis
Thanks++,

--

,--. Bernard Klein, Berlin, Germany ,= ,-_-. =.
/ ,- ) ((_/)o o(\_))
\ `-' `-'(. .)`-'
`-. \_/

Jul 22 '05 #8
On 2004-04-17, Bernard <ob**********@e lsewhere.net> wrote:
From: http://www.nicemice.net/cexcept/

\begin{quotatio n}

cexcept
Cosmin Truta and I have developed a try/catch/throw exception-handling
interface for C. It basically works the way you would expect:

Try {
/* Maybe a Throw statement will be executed */
/* (maybe within a deeply nested function): */
/* Throw e; */
/* If so, execution jumps to the catch clause. */
}
Catch (e) {
/* An exception was thrown and copied into e. */
}

The interface of the latest release is fully implemented and
documented in cexcept.h.

\end{quotation}

does have try-catch but not throw syntax. I want to first absorb the
syntax and then its semantic meaning in terms of program flow. C code,
requested in original post, was just a language that I knew well.


It doesn't seem like you tried to read the source code in the
cexcept.h file. If you understand C, then read the code. If
you don't understand the C code, post your C question to
comp.lang.c.

-- James
Jul 22 '05 #9
James Hu wrote:
.... snip ...
It doesn't seem like you tried to read the source code in the
cexcept.h file. If you understand C, then read the code. If
you don't understand the C code, post your C question to
comp.lang.c.


Since people seem to refuse to cut the cross-postings out, the
only thing left to do is to PLONK this thread.

--
fix (vb.): 1. to paper over, obscure, hide from public view; 2.
to work around, in a way that produces unintended consequences
that are worse than the original problem. Usage: "Windows ME
fixes many of the shortcomings of Windows 98 SE". - Hutchison

Jul 22 '05 #10

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

Similar topics

4
5080
by: Murat Tasan | last post by:
i am implementing a custom version of the java.util.Map interface. my custom version does some encryption stuff when making modifications to the map via one of the 4 modification methods (put, putAll, remove, and clear). in doing this, i would like to also use one of my own exception objects... so these 4 methods in the custom version should now also be defined with: throws EncryptionException because EncryptionException is not a...
16
5297
by: David Turner | last post by:
Hi all I noticed something interesting while testing some RAII concepts ported from C++ in Python. I haven't managed to find any information about it on the web, hence this post. The problem is that when an exception is raised, the destruction of locals appears to be deferred to program exit. Am I missing something? Is this behaviour by design? If so, is there any reason for it? The only rationale I can think of is to speed up...
21
2241
by: dkcpub | last post by:
I'm very new to Python, but I couldn't find anything in the docs or faq about this. And I fished around in the IDLE menus but didn't see anything. Is there a tool that can determine all the exceptions that can be raised in a Python function, or in any of the functions it calls, etc.? /Dan
26
2922
by: OvErboRed | last post by:
I just read a whole bunch of threads on microsoft.public.dotnet.* regarding checked exceptions (the longest-running of which seems to be <cJQQ9.4419 $j94.834878@news02.tsnz.net>. My personal belief is that checked exceptions should be required in .NET. I find that many others share the same views as I do. It is extremely frustrating to have to work around this with hacks like Abstract ADO.NET and CLRxLint (which still don't solve the...
9
2344
by: Gianni Mariani | last post by:
I'm involved in a new project and a new member on the team has voiced a strong opinion that we should utilize exceptions. The other members on the team indicate that they have either been burned with unmaintainable code (an so are now not using exceptions). My position is that "I can be convinced to use exceptions" and my experience was that it let to code that was (much) more difficult to debug. The team decided that we'd give...
15
426
by: Bernard | last post by:
Hi All, I am not sure if I should be asking this question on clc or clc++. Let me try on both. I hope that this is not too trivial for the brilliant minds over here. I know that OOP questions have been asked on clc before so it is probably OK. I am a newbie to C++. BS 3rd edition states: % The throw transfers control to a handler for exceptions .... %
70
11697
by: Rajan | last post by:
Hi, I am trying to simulate a memcpy like this void* mem_cpy(void* dest, void* src, int bytes) { dest = malloc(bytes); } Now if I want to copy the bytes from src to dest, how do I copy these bytes. I am stuck here.
6
2835
by: RepStat | last post by:
I've read that it is best not to use exceptions willy-nilly for stupid purposes as they can be a major performance hit if they are thrown. But is it a performance hit to use a try..catch..finally block, just in case there might be an exception? i.e. is it ok performance-wise to pepper pieces of code with try..catch..finally blocks that must be robust, in order that cleanup can be done correctly should there be an exception?
1
2397
by: Anonieko | last post by:
Understanding and Using Exceptions (this is a really long post...only read it if you (a) don't know what try/catch is OR (b) actually write catch(Exception ex) or catch{ }) The first thing I look for when evaluating someone's code is a try/catch block. While it isn't a perfect indicator, exception handling is one of the few things that quickly speak about the quality of code. Within seconds you might discover that the code author...
0
6509
RedSon
by: RedSon | last post by:
Chapter 3: What are the most common Exceptions and what do they mean? As we saw in the last chapter, there isn't only the standard Exception, but you also get special exceptions like NullPointerException or ArrayIndexOutOfBoundsException. All of these extend the basic class Exception. In general, you can sort Exceptions into two groups: Checked and unchecked Exceptions. Checked Exceptions are checked by the compiler at compilation time. Most...
0
9682
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
10871
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10621
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10268
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...
0
9396
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6998
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5668
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
5846
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4039
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.