[lug] Re: g++ signals and exceptions question

Matt Armstrong matt at lickey.com
Wed May 15 14:22:49 MDT 2002

Jonathan Briggs <zlynx at acm.org> writes:

> I was thinking that it would be pretty neat if a C++ program could
> catch a signal and raise an exception.

Yeah, the utility of that is pretty clear.  E.g. set up SIGALARM, run
some code, and if your code takes too long it'd break out with a
Timeout exception.

The Ruby scripting language lets one thread send another thread an
exception at any time.  But Ruby is interpreted, so it is basically
implemented by setting a variable in the thread which is checked at
the next convenient time by the interpreter.

> I tried throwing an exception from a signal handler, but that only
> resulted in a messy crash.  I'm sure this is because signal handlers
> use a completely different program stack while running.

They use the same program stack, which is part of the problem.  The
signal can happen at any time -- any machine instruction.  C++ object
code isn't set up to handle exceptions at that granularity.

> Functions such as siglongjmp can manipulate the original program
> stack and go somewhere else.  Does anyone know of a C++ (it can be
> g++ / Linux specific) function or library that would allow raising
> an exception from a signal handler?
> If it doesn't exist, I might try writing it.

I think it is basically impossible to implement the idea in C++.
You'd need support from the compiler, and that support would basically
implement the "check a global variable" trick at, say, every function
call or entry into every basic block.

> Do any of you who are experienced C++ programmers see anything wrong
> with this idea?  One problem I thought of is that it might violate
> exception restrictions (functions that declare they will never
> throw, or will only throw exceptions of type int, for example.)

That's a good point too.

Don't send mail to Albert.Lancing at hole.lickey.com
The address is there for spammers to harvest.

More information about the LUG mailing list