21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Exception handling essentially acts as an alternate return mechanism, designed particularly<br />

for conditions that signify an abnormal state.<br />

You can also perform exception handling in C using macros. The safe string-handling<br />

library from Recipe 3.4 includes an exception-handling library named XXL.<br />

This exception-handling library is also available separately at http://www.zork.org/<br />

xxl/.<br />

The XXLlibrary only allows you to throw integer exception codes. However, when<br />

throwing an exception, you may also pass arbitrary data in a void pointer. The XXL<br />

syntax attempts to look as much like C++ as possible, but is necessarily different<br />

because of the limitations of C. Here is an example:<br />

#include "xxl.h" /* Get definitions for exception handling. */<br />

void sample(void) {<br />

TRY {<br />

somefunc( );<br />

}<br />

CATCH(1) {<br />

/* Handle exception code 1. */<br />

}<br />

CATCH(2) {<br />

/* Handle exception code 2. */<br />

}<br />

EXCEPT {<br />

/* Handle all other exceptions... if you don't do this, they get propogated up<br />

to previous callers. */<br />

}<br />

FINALLY {<br />

/* This code always gets called after an exception handler, even if no<br />

* exception gets thrown, or you raise a new exception. Additionally, if no<br />

* handler catches the error, this code runs before the exception gets<br />

* propogated.<br />

*/<br />

}<br />

END_TRY;<br />

There are a number of significant differences between XXLand C++ exception handling:<br />

• In XXLyou can only catch a compile-time constant integer, whereas in C++ you<br />

can catch based on a data type. That is, catch(2) is invalid in C++. There, you<br />

would catch on the entire integer data type, as with catch(int x). You can think<br />

of CATCH( ) in XXL as a sort of case statement in a big switch block.<br />

• XXLhas the EXCEPT keyword, which catches any exception not explicitly caught<br />

by a catch block. The EXCEPT block must follow all CATCH( ) blocks. XXL’s EXCEPT<br />

keyword is equivalent to CATCH(...) in C++.<br />

• XXLhas a FINALLY block, which, if used, must follow any exception-handling<br />

blocks. The code in one of these blocks always runs, whether or not the excep-<br />

702 | Chapter 13: Other Topics<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!