PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Implementing Exceptions Using setjmp/longjmp

Working on my first Pocket PC game, I found myself yearning for better error handling in my code base. Normally, I'd just use standard C++ exceptions, but eVC++ 3 doesn't support them.

Once I learned how setjmp/longjmp worked, I ended up rolling my own very simple exception-like framework.

I wanted my code to look like this:

Code:

TRY
{
TRY
{
THROW(Exception::CodeB);
}
CATCH (Exception::CodeB)
{
RETHROW;
}
END_TRY_CATCH
}
CATCH (Exception::CodeA)
{
}
CATCHALL
{
}
END_TRY_CATCHALL


I implemented this mechanism using macros. I'll get to the macro expansion in a bit, but first I'll explain the few globals I use.

I ended up using a simple class with enums for the exception codes, and a few static members. (It needn't be a class, for use in C.)

Code:

class Exception
{

public:

enum
{
CodeA = 1,
CodeB
};

static
jmp_buf m_aEnv[EXCEPTION_MAX];

static
int m_nDepth;

static
int m_nCode;

};


Now, the try/catch macros merely use setjmp in switch statements to organize the code:

Code:

#define TRY \
{ \
++Exception::m_nDepth; \
switch (setjmp(Exception::m_aEnv[Exception::m_nDepth])) \
{ \
case 0: \
{


#define CATCH(nCode) \
break; \
} \
case nCode: \
{


#define CATCHALL \
break; \
} \
default: \
{ \


#define END_TRY_CATCHALL \
break; \
} \
} \
--Exception::m_nDepth; \
}


#define END_TRY_CATCH \
CATCHALL \
{ \
RETHROW; \
} \
END_TRY_CATCHALL


The throw/rethrow macros use longjmp to do the jumping:

Code:

#define THROW(nCode) \
longjmp(Exception::m_aEnv[Exception::m_nDepth], Exception.m_nCode = nCode)


#define RETHROW \
longjmp(Exception::m_aEnv[--Exception::m_nDepth], Exception.m_nCode)


How does it work?

Basically, each CATCH becomes a case in a statement switching on the return code of setjmp. Case 0 is the TRY code; other cases use the exception code, and are the result of a longjmp. The default case does the CATCHALL. If there's no catchall, it automatically does a rethrow.

When you enter a TRY block, a jump environment is put on the stack. When you THROW, you longjmp to that jump environment to the case for the exception code (or the default case), and the jump environment is removed from the stack.

Auto objects are not destroyed as they are in real C++ exception handling. Also, I wouldn't do something like return from within a TRY block; it will mess up the jump environment stack.

This could be done in C easily. As it is, you only need to include <csetjmp> and define EXCEPTION_MAX for it to work. (I had troubles putting jmp_buf into other containers, so I just used an array.)

If you want messages, you could put them in the Exception class. You could also tie them into the THROW macro.

The beauty of my mechanism is that it is quite simple, once you understand how setjmp/longjmp work, and figure out the macros. I looked at some other exception implementations after making mine, and they all seemed too complicated.
mlepage · 24 Aug 2003, 04:13 UTC — Testing the Mechanism
I did some testing of my exception-like mechanism. First, here is an exception testing helper function, which essentially throws exceptions based on its parameters and records its progress through try/catch blocks.

Code:

int
testExceptionHelper(
const int knThrow,
const int knCode)
{
int nResult = 0;

TRY
{
nResult |= 1<<0;
if (knThrow == 1<<0) THROW(knCode);
TRY
{
nResult |= 1<<1;
if (knThrow == 1<<1) THROW(knCode);
}
CATCH (1)
{
nResult |= 1<<2;
}
CATCH (3)
{
nResult |= 1<<3;
RETHROW;
}
END_TRY_CATCH
nResult |= 1<<4;
if (knThrow == 1<<4) THROW(knCode);
}
CATCH (1)
{
nResult |= 1<<5;
}
CATCH (2)
{
nResult |= 1<<6;
}
CATCHALL
{
nResult |= 1<<7;
}
END_TRY_CATCHALL

return nResult;
}


Now, here is the test code that puts the helper through its paces. (CHECK is just a macro I have that ensure the test passes.)

Code:

void
testException()
{
CHECK(testExceptionHelper(0, 1) == (1<<0|1<<1|1<<4));

CHECK(testExceptionHelper(1<<0, 1) == (1<<0|1<<5));
CHECK(testExceptionHelper(1<<0, 2) == (1<<0|1<<6));
CHECK(testExceptionHelper(1<<0, 3) == (1<<0|1<<7));
CHECK(testExceptionHelper(1<<0, 4) == (1<<0|1<<7));

CHECK(testExceptionHelper(1<<1, 1) == (1<<0|1<<1|1<<2|1<<4));
CHECK(testExceptionHelper(1<<1, 2) == (1<<0|1<<1|1<<6));
CHECK(testExceptionHelper(1<<1, 3) == (1<<0|1<<1|1<<3|1<<7));
CHECK(testExceptionHelper(1<<1, 4) == (1<<0|1<<1|1<<7));

CHECK(testExceptionHelper(1<<4, 1) == (1<<0|1<<1|1<<4|1<<5));
CHECK(testExceptionHelper(1<<4, 2) == (1<<0|1<<1|1<<4|1<<6));
CHECK(testExceptionHelper(1<<4, 3) == (1<<0|1<<1|1<<4|1<<7));
CHECK(testExceptionHelper(1<<4, 4) == (1<<0|1<<1|1<<4|1<<7));
}


This pretty much tests all paths through the nested try/catch blocks. They all pass the test!
I've been using this now for a week or two and I'd just like to say it's working fine.
angedelamort · 03 Sep 2003, 13:13 UTC
It's been a while I didn't come here, but after reading the thread title, I remember reading something about that. Here something that looks like what I've read:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vccore98/html/_core_using_setjmp.2f.longjmp.asp

But I have to say that it's a really nice and simple implementation of the try catch system you've made there. But I learned in your post that try/catch is not working in EVC :P So I think it's excusable.
Your implementation is very clean but there are a few things you could consider that would provide some value without really making things that much worse.

One common technique is to rely a bit on automatic objects on the stack to do the chaining of jmp_buf:s. Basically, you keep track of the last such object through a global variable and that object is chained to its parent. When the object is
automatically destroyed it updates the global variable to point to its parent and performs a rethrow if necessary. These objects and the jmp_buf:s themselves are allocated on the stack this way.

This provides:
* Not necessary to choose a certain maximum depth for try catch statements.
* Ability to safely use the return statement in try and catch blocks. This is mainly a readability issue but something that I personally value.

You may want to add some code that checks that the exception depth has not exceeded the maximum. This happens easier than you may think in certain cases and you typically get very strange errors if you dont protect yourself against it. The cost of checking that is also very low.

You could consider making it thread-safe by making the global things thread-local instead.
But are stack objects (auto storage) automatically destroyed when a longjmp occurs? I didn't think they were, but I can't say I know for sure. Doesn't your method rely on that? I wanted to do something like that, but wasn't sure it was possible.

There's lots of fancy exception implementations out there, I kind of like mine for being extremely simple.

By all means check for try/catch depth if you have nested code. So far I'm not heavily nesting code that uses exceptions, so I'm fairly safe from that particular problem.
No, stack object will not be automatically destroyed when a longjmp occurs. But since the try-catch are unwinded by the longjmp:s one level at a time, you will never longjmp "across" one of those automatic objects. I hope that explanation makes sense...

Basically, you get
Code:

{ // begin try scope
ChainedExceptionContext ex_object; // automatic object
switch (setjmp(ex_object.jmp_buf))
{
case 0:
// things inside the try block go here
if(someMethod())
return -1;
case x: ...
// handle exceptions here, figure out
// which one it is and so on...
}
} // end try scope, automatic object will be destroyed however this scope is left.


If someMethod throws an exception we'll end up in the exception cases and the automatic object will still be valid. If the "return -1" statement is executed the automatic object will be destroyed and the destructor can handle the necessary book keeping (i.e. updating the global variable that keep tracks of the last ChainedExceptionContext.

It takes a little thought to get things right and avoid longjmp:ing over the automatic object but it is possible... and enjoyable if you like that sort of thing.

This all depends a bit on the code that implements the exception handling not throwing exceptions itself but that is usually the case since that typically complicates things alot if it is allowed.
OK, I see what you're saying.

Instead of longjmping and leaving all those auto objects undestroyed, do a return, destroying the auto objects, one of which knows to do a longjmp.

Auto objects are destroyed in reverse order of construction, so wouldn't it have to be the first object allocated?
Well, this solution doesn't handle auto objects in general. It's more of a trick, designing the exception handling code so that the specific auto objects that are used for exception handling are destroyed. (This is done by not longjmp:ing across those particular auto objects). The reason for it is to get the ability to use return statements in the try/catch blocks.

There will typically only be one such exception handling autoobject per try block and the order of destruction will be correct. I'm not sure I understand what you mean about it having to be the first object allocated.
If you're only trying to allow return, it doesn't matter which order the objects are in.

But if you're trying to handle auto object deletion, then you'd want your housekeeping object to be the first created in the function. Then it would be the last destroyed when returning from the function. All the other auto objects would be destroyed, before the housekeeping object does its longjmp.

I believe this would provide for auto object deletion in cases where an exception occurs in the try block, whether you catch it or not, because in either case the exception is jumping to that try block. If you handle the exception you continue from there, and if you don't you return and then do another longjmp (after the auto objects are destroyed).

But it wouldn't handle exceptions that occur when not in the try block, since they would not make a stop at this function when they longjmp. In C++ these objects are still destroyed during stack unwinding.

I suppose you could enclose every function in a try block, or just automate the process entirely with these housekeeping objects. But that's a little bit heavyweight for me. This is just to tide me over till C++ supports PPC 2002 development, or everyone upgrades to PPC 2003.