TweetFollow Us on Twitter

March 96 - Using C++ Exceptions in C

Using C++ Exceptions in C

Avi Rappoport

Exception handling in C++ offers many advantages over error handling in C. Using the techniques outlined here, you can implement C++ exceptions in your C code without a lot of effort. The payback is streamlined debugging that can result in more error-free code. When your program encounters errors, it jumps to the appropriate error-handling section, rather than dealing with the error locally. This simplifies your design and helps you concentrate on the normal flow of control. Centralized error handling also makes it easier to improve your reporting and feedback mechanisms incrementally.

I wrote a few little XCMDs in C and after the fifteenth crash of the day, I decided that I'd better add some error handling. So I looked at Dartmouth XCMDs, but I wasn't impressed. Each check for an error meant another indentation in the code, and I was worried about disposing of handles correctly as I passed errors up the call chain. Since I'd been looking at a lot of C++ lately, I wondered whether I couldn't use part of the C++ exception-handling mechanism to avoid problems in my code. It worked pretty well, so I thought I'd share my results.

For part of my solution, I used some Metrowerks macros. Metrowerks has graciously allowed these helpful exception and debugging source, header, and resource files to be included on this issue's CD, so you can use them without purchasing its CodeWarrior CD. The files contain macros that provide convenient tools for implementing exceptions and debugging signals, as well as an alert resource that can provide information during debugging.

Although I've used C++ exception handling in my C code with great results, I'd like to offer you one word of caution before you use them. Realize that C++ is not strictly an extension of C; as a result, in some cases it's possible that the program may not behave as you think it should.


All programs must respond to system and subroutine failures somehow. For example, many Macintosh Toolbox routines return a variable of type OSErr, while others require that you call Toolbox routines (such as MemError and ResError) to retrieve the error. If you ignore system and subroutine failures, your program is practically guaranteed to crash.

Good error handling allows you to cope with many kinds of problems. Your checks can trigger other code that deals with the problem (for example, by freeing memory). During debugging, error checking should notify you that something has gone wrong. And since you can't, unfortunately, catch all the bugs during testing, you must also set up an error-reporting mechanism to notify your users when something has gone wrong. In the worst case, your error handling should at least ensure that your program exits gracefully, without losing or corrupting user data.


The American National Standards Institute (ANSI) has defined a mechanism for C++ compilers that allows code to "throw" exceptions. When the compiler encounters a throw statement, it jumps to the nearest catch statement. (The "nearest" catch statement is the one associated with the current try statement, whether it's in the current routine or farther up the call chain.) The catch statement can deal with the error, pass it up the call chain, or both. A throw statement should appear only within a try or catch statement or in code called from within a try statement. Listing 1 shows these basic components.

Listing 1. Throwing exceptions

OSErr theErr = noErr;

// Try block.
try {
   // Do something.
   // If error, throw an exception.
   if (theErr != noErr)
      throw (theErr);
// Catch blocks.
catch (OSErr theErr) {
   // Do something with the error.
catch (...) {
   // Catch anything else.
As shown in Listing 1, exceptions are dealt with in catch blocks, which take an appropriate action depending on the error. For serious errors, this means cleaning up and terminating the program. For less serious errors, the catch block could continue without making a fuss, or make changes based on the error and again call the routine that threw the error; sometimes you might want to throw a more generic error, which is caught and interpreted in a higher-level catch block. I also recommend using the Metrowerks signal macros (described later) within your catch blocks to help you locate errors during debugging.
    The three dots in catch (...) are actually in the code; the other such dots that appear in these listings are ellipses representing code that isn't shown.*
When carefully designed, C++ exception handling in your program can deal with problems at an appropriate level. As you may already have guessed, this feature is both powerful and dangerous. The advantage is that you don't have to mess around with returning errors for every routine or indenting deeply. However, if you allocate memory, you must be careful to dispose of it at the right time or it will cause a leak.


To add C++ exceptions to your code, you must do the following:
  • Force the use of the C++ compiler.
  • Create a top-level exception handler in your main routine.
  • Define try blocks and catch blocks, and call throw at appropriate times.
  • Add the C++ library (CPlusPlus.lib, CPlusPlusA4.lib, or MWCRuntime.Lib) to your project.
The Metrowerks macros that you'll see in the code that follows make implementing exception handling much easier than it would be otherwise. I'll talk about them later.


To use C++ exceptions, you have to force the use of the C++ compiler. In Metrowerks CodeWarrior, the easiest way is to select the Activate C++ Compiler checkbox in the C/C++ Language panel. You should also make sure that the Enable C++ Exceptions checkbox is selected, because it enables throwing exceptions rather than direct destruction (one of those weird C++ things). An alternative way to invoke the compiler is to change the extension on your source code files to ".cp" or by changing the Target panel preferences; however, the checkbox method is the easiest.

C++ is stricter about automatic parameter conversion than C, so selecting the MPW Pointer Type Rules checkbox in the C/C++ Language panel avoids a bunch of errors (it forces the compiler to allow some implicit char* casts). But you'll get errors for other parameters and return values, so you have to clean them up as indicated by the compiler. For example, the following is an error message returned by a C++ compiler:

HC2RTF.c line 224  textLen = strlen(textString);
Error   : cannot convert
'unsigned char *' to
'char *'
To fix this problem, you can change the code to
textLen = strlen((char *) textString)
The CodeWarrior C++ compiler puts special C++ information into function names (this is called name mangling). C doesn't do this, so header files for C functions should be surrounded by #extern "C" statements to tell the compiler not to mangle these names (see Listing 2). The Macintosh Toolbox header files take care of this already.

Listing 2. Preventing name mangling

#ifdef __cplusplus
extern "C" {

long   FindBreak(char* buffer, short len);
// More declarations here

#ifdef __cplusplus


In your main loop or function, you should specify the top-level exception handler. This should catch serious errors, report them, and exit gracefully. Listing 3 shows the simplest possible exception handler (which you'll understand better as you read on).

Listing 3. Simple top-level exception handler

pascal void main(XCmdPtr paramPtr)
   long   oldA4 = SetCurrentA4();

   try {
   catch (...) {
      ReportError("\pSerious error occurred.")
      // XCMDs do not have to use ExitToShell. 


When you use a try statement, it tells the compiler that the following code might have exceptions thrown in it. All functions that throw exceptions must be within a try block, either in the current function or in a calling function. It's pretty easy to set up try blocks before catch blocks. This is good, because you do have to do it: any throws that aren't caught will automatically abort the program.


You should have catch blocks for each error type. So, for example, you might define catch (OSErr theErr), catch (errStruct errRecord), and catch (Str255 theErr). You should also have a generic catch, catch (...), which doesn't have any parameters, to catch exceptions of all other types. Although it's better to use typed catches that handle specific errors, always add at least one generic catch and have it signal an error with an alert or break to the debugger. This will help you catch exception mistakes during your debugging and testing phase. Listing 4 shows examples of these types of catch blocks.

Listing 4. Specific and generic catch blocks

catch (StringPtr errString) {
   // If HandleError throws, it will be caught above this catch. 
catch (OSErr theErr) {
   Str255 errString;
   ConvertErrToString(theErr, errString);
   throw (theErr);   // Rethrow to handle error.
// Forces the application to quit after the message.
catch (...) {
   SignalPStr_("\pUntyped error occurred in prefs.") 
The compiler automatically routes the error to the appropriate catch statement, depending on the parameter passed to the throw statement. In Listing 4, both the StringPtr and OSErr types are caught specifically, after which they're reported. The OSErr catch rethrows the error as well. Any other types of errors are caught by the generic catch, which calls a signal macro to display a message and then exits the program.

You can, and often should, continue after catching an error. For example, after a disk full error, you should allow the user to choose a different volume. Note that the program will continue after the catch block, rather than in the location where the exception was thrown.


Many of your low-level routines may call the Macintosh Toolbox or otherwise interact with the Mac OS. They should throw an exception if there's an error, as shown in Listing 5.

Listing 5. Throwing exceptions for Macintosh Toolbox errors

void MakeMyResFile(Str32 fileName)
   // Could also use the Metrowerks ThrowIfResError_ macro.
   err = ResError();
   if (err <> noErr)
      throw (err);
   // Continue with execution.

// Call the function.
   try {
   catch (OSErr theErr) {
      if (theErr == dupFNErr) {
         // Do something; file already exists.
         throw (theErr);   // Rethrow the error.
   }   // End catch statement.
So where do you catch these exceptions? Remember, they percolate up the call chain until they find a catch statement, so you don't have to take care of them in the immediate calling function (unless you've allocated memory or done other things that need undoing). When you catch them, you can, and sometimes should, throw the error again. You can either report errors in mid-level routines or rethrow them up to a higher-level error reporting mechanism.

In addition to these catch statements, be sure to add a catch statement in circumstances where you need to do any of the following:

  • Dispose of handles and otherwise deallocate memory.
  • Shut down something you started in the try block, such as opening a file.
  • Change the error thrown.
For your own functions, you should throw errors in situations that can cause serious problems or crash the machine. For instance, if you're providing a function that accesses a variable-length array that contains 16 members and the caller asks for the 17th member, you can throw a range error. There's no hard-and-fast rule about when to put the error checking into a function and when to require it before calling -- it depends on the situation. For example, if you're calling a function inside a tight graphics loop only and you want speed, you can probably check the parameters sufficiently in the calling function. However, if you have a utility routine that's called from several sections of your code, adding error checking will help you remember its requirements, such as parameters, memory, and other system states, to avoid problems later on.

Handling exceptions in libraries is tricky because you don't know much about the calling program. Think carefully about what you should report to the user and what you should simply return to calling functions.

As your programs become more sophisticated, you can start working around certain errors -- for example, by using temporary memory when the application's heap is full. You'll also need to design interactive error reporting, allowing your users to take action (such as unlocking a locked disk) when they can. Then your application can continue properly.


The Metrowerks PowerPlant UDebugging and UException files, included on this issue's CD, provide convenient tools for throwing common exceptions and alerting you during debugging. To use them, put the folder in your project folder, add the sources and the "PP DebugAlerts.rsrc" resource file to your project, and include the headers in your source files.

The UException.h file includes macros that automate common exception conditions. The UException.cp file includes an abort function. The UDebugging.h file defines some macros that make locating problems easier by allowing you to specify a signal, a debugging string displayed when the macro is invoked.

    If your project includes an ANSI library you don't need to add UException.cp. The abort function will conflict.*


You need to set the global variables gDebugThrow and gDebugSignal in UDebugging.h to specify the debugging actions for throws and signals. By default, they're set to do nothing at all. Other options include displaying a dialog, dropping into the source-level debugger, or dropping into the low-level debugger. To activate the macros, be sure to define Debug_Signal in your precompiled header or UDebugging.h.

The following are the global variable options:

  • debugAction_Nothing -- Do nothing.
  • debugAction_Alert -- Display an alert box with an exception code (described later), filename, and line number where the throw or signal was made. For this to work, you must include the file "PP DebugAlerts.rsrc" in your project.
  • debugAction_SourceDebugger -- Break into the source-level debugger. For the Metrowerks source-level debugger, execution will stop with the arrow pointing to the line containing the throw statement. The exception code isn't displayed. You can check the display of variable values in the source-level debugger for that information. (I've tested this with the Metrowerks debugger only.) If you aren't running under the source-level debugger, debugAction_SourceDebugger will break into the low-level debugger on PowerPC processor-based machines, but might crash on 680x0 systems.
  • debugAction_LowLevelDebugger -- Break into MacsBug and display the exception code as a string. In MacsBug, the console will display two lines:
User Break at routine + offset
exception code 
  • Note that if you don't have a low-level debugger installed, your program will crash with an unimplemented trap error if it tries to break into the low-level debugger.


UException.h defines several useful macros that automatically perform tests and throw exceptions if a test failed. It also defines a type, ExceptionCode (a long), and two standard exceptions, err_AssertFailed ('asrt') and err_NilPointer ('nilP'), which are treated as type ExceptionCode. Here are the throw macros:
  • ThrowIf_(test) -- Throws an exception if test is true, where test is a Boolean or the result of a Boolean condition. The exception code will be err_AssertFailed.
  • ThrowIfNot_(test) -- Throws an exception if test is false. The exception code will be err_AssertFailed.
  • ThrowIfOSErr_(err) -- Throws an exception if err isn't equal to noErr.
  • ThrowOSErr_ (err), FailOSErr_ (err) -- Throws an exception with err as the exception code.
  • ThrowIfNULL_(ptr), ThrowIfNil_(ptr), FailNil_(ptr) -- If ptr is NULL (or nil), throws an exception with err_NilPointer as the exception code.
  • ThrowIfMemError_() -- Calls the Toolbox routine MemError and throws an exception if it returns a result that's not equal to noErr; the MemError return becomes the exception code.
  • ThrowIfMemFail_(p) -- Throws an exception if p (a pointer or a handle) is nil. The MemError routine is used to check the success or failure of the last Memory Manager call. If MemError returns a result that's not equal to noErr, the exception code is set to the return value of the MemError call. If MemError returns noErr, the exception code is set to memFullErr, a constant defined by Apple.
  • ThrowIfResError_() -- Calls the Toolbox routine ResError and throws an exception if it returns a result that's not equal to noErr; the result becomes the exception code. ResError is used to check the success or failure of the last Resource Manager call.
  • ThrowIfResFail_(h) -- Throws an exception if h (a handle to a resource) is nil. If ResError returns a result that's not equal to noErr, the exception code is set to that result. If ResError returns noErr, the exception code is set to resNotFound, a constant defined by Apple.
You can use all of the macros within if-else clauses, as they're designed to be self-contained. For example:
if (err != fnfErr)


UDebugging.h defines macros for raising signals, also known as asserts. These will stop the execution of the program and report errors. You can use them to check for nil pointers, out-of-range offsets, excess length, division by zero, and other problems. If you remove the definition of Debug_Signal, the entire set of macros is converted to white space and takes no runtime overhead whatsoever.

The macros are defined to check gDebugSignal for the action to take on execution, as described previously.

The following are the signal macros:

  • SignalPStr_(pstr) takes a Pascal string argument. The string can be a literal Pascal string (in double quotes beginning with \p) or a StringPtr variable (and its variants, such as Str255).
  • SignalCStr_(cstr) takes a literal C string argument. The string must be a literal (text within double quotes) and can't be a char*. Because the underlying Toolbox routines take Pascal strings, the SignalPStr_ macro is more efficient.
  • SignalIf_(test), SignalIfNot_(test) each take a Boolean condition as an argument and raise a signal depending on whether the condition is true or false.
  • Assert_(test) is a synonym for SignalIfNot_(test).


C++ exceptions and these Metrowerks macros make error handling reasonably easy to add to most programs. With a little thought, you can design a clean structure for dealing with Mac OS errors and internal errors -- a structure that's easily extensible to new code. You can avoid stress during testing by adding signal macro calls for common errors throughout your code. They're much easier to debug than system crashes. And yes, thank you, my XCMDs are much better now!


    • For a more in-depth examination of exceptions in C++, consult the article "Try C++ Exception Handling" by Kent Sandvik (MacTech Magazine, October 1995). For another view of C exceptions, see "Living in an Exceptional World" by Sean Parent in develop Issue 11.
    • For information on the return values of Macintosh Toolbox routines and the error codes, see the Inside Macintosh series, Macintosh Programmer's Toolbox Assistant, and THINK Reference. You can also look at the header file Errors.h.

    Because C has no objects, when you read these publications, you can ignore all discussions of object throwing, exception objects, construction, and destruction.

AVI RAPPOPORT has degrees in medieval studies and library/information studies, so she feels well qualified to work in the Macintosh software industry. In her job as user advocate and publications coordinator at Metrowerks, she spent her time documenting PowerPlant, making conference calls, and frantically trying to check CodeWarrior CDs before they were burned. Avi now works at StarNine as product manager for messaging products. She lives in Berkeley, California, with her Mac/Web scripter husband and their four-year-old son -- all BMUG members.*

Thanks to Greg Dow, Pete Gontier, Tom Lippincott, and Jon Wätte for their C++ wizardry and personal patience, and to Pete and Tom for reviewing this article.*


Community Search:
MacTech Search:

Software Updates via MacUpdate

AirPort Utility 6.3.6 - Set up and manag...
Note: Most recent release available only within OS X 10.11 El Capitan update. Use AirPort Utility to set up and manage your Wi-Fi network and AirPort base stations, including AirPort Express, AirPort... Read more
Quicksilver 1.3.1 - Application launcher...
Quicksilver is a light, fast and free Mac application that gives you the power to control your Mac with keystrokes alone. Quicksilver allows you to find what you need quickly and easily, then act... Read more
Tidy Up (Five Users) 4.1.5 - Find duplic...
Tidy Up is a complete duplicate finder and disk-tidiness utility. With Tidy Up you can search for duplicate files and packages by the owner application, content, type, creator, extension, time... Read more
Mellel 3.4.3 - The word processor of cho...
Mellel is the leading word processor for OS X and has been widely considered the industry standard since its inception. Mellel focuses on writers and scholars for technical writing and multilingual... Read more
Skype - Voice-over-internet p...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more
Bookends 12.6.0 - Reference management a...
Bookends is a full-featured bibliography/reference and information-management system for students and professionals. Access the power of Bookends directly from Mellel, Nisus Writer Pro, or MS Word (... Read more
Apple iBooks Author 2.4 - Create and pub...
Apple iBooks Author helps you create and publish amazing Multi-Touch books for iPad. Now anyone can create stunning iBooks textbooks, cookbooks, history books, picture books, and more for iPad. All... Read more
Web Snapper 3.3.9 - Capture entire Web p...
Web Snapper lets you capture Web pages exactly as they appear in your browser. You can send them to a file as images or vector-based, multi-page PDFs. It captures the whole Web page - eliminating the... Read more
Tunnelblick 3.6beta10 - GUI for OpenVPN...
Tunnelblick is a free, open source graphic user interface for OpenVPN on OS X. It provides easy control of OpenVPN client and/or server connections. It comes as a ready-to-use application with all... Read more
EtreCheck 2.5.1 - For troubleshooting yo...
EtreCheck is a simple little app to display the important details of your system configuration and allow you to copy that information to the Clipboard. It is meant to be used with Apple Support... Read more

Camel Up (Games)
Camel Up 1.0.0 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.0 (iTunes) Description: | Read more »
The Martian: Bring Him Home (Games)
The Martian: Bring Him Home 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Based on the best selling novel and critically acclaimed film, THE MARTIAN tells the story of Astronaut Mark... | Read more »
This Week at 148Apps: September 21-30, 2...
Leap Into Fall With 148Apps How do you know what apps are worth your time and money? Just look to the review team at 148Apps. We sort through the chaos and find the apps you're looking for. The ones we love become Editor’s Choice, standing out above... | Read more »
Tweetbot 4 for Twitter (Social Networki...
Tweetbot 4 for Twitter 4.0 Device: iOS Universal Category: Social Networking Price: $4.99, Version: 4.0 (iTunes) Description: *** 50% off for a limited time. *** | Read more »
Mori (Games)
Mori 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Stop, rewind and unwind with Mori. Time is always running, take a moment to take control. Mori is an action puzzle game about infinitely... | Read more »
100 Years' War (Games)
100 Years' War 1.0 Device: iOS Universal Category: Games Price: $3.99, Version: 1.0 (iTunes) Description: | Read more »
Tower in the Sky (Games)
Tower in the Sky 0.0.60 Device: iOS Universal Category: Games Price: $1.99, Version: 0.0.60 (iTunes) Description: | Read more »
hocus. (Games)
hocus. 1.0.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0.0 (iTunes) Description: New, polished, mind-bending, minimal puzzle game with dozens of levels and extra-ordinary design Features:- Beautifully crafted... | Read more »
Mos Speedrun 2 (Games)
Mos Speedrun 2 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Mos is back, in her biggest and most exciting adventure ever! Wall-jump to victory through 30 mysterious, action packed levels... | Read more »
3D Touch could be a game-changer, but it...
Were you one of the lucky/financially secure enough ones to buy a new iPhone 6s or iPhone 6s Plus over the weekend? Yup, me too (I’m not convinced I was either of those two things, but let’s go with lucky for now), so I thought I’d delve into just... | Read more »

Price Scanner via

Apple refurbished iPad Air 2s available for u...
Apple has Certified Refurbished iPad Air 2s available for up to $140 off the price of new models. Apple’s one-year warranty is included with each model, and shipping is free: - 128GB Wi-Fi iPad Air 2... Read more
Save up to $100 on Mac AppleCare Protection P...
Adorama has 3-Year AppleCare Warranties on sale for up to $100 off MSRP including free shipping plus NY & NJ sales tax only: - Mac Laptops 15″ and Above: $249 $100 off MSRP - Mac Laptops 13″ and... Read more
Updated Mac Price Trackers
We’ve updated our Mac Price Trackers with the latest information on prices, bundles, and availability on systems from Apple’s authorized internet/catalog resellers: - 15″ MacBook Pros - 13″ MacBook... Read more
12-inch MacBooks in stock for up to $120 off,...
Adorama has 12″ Retina MacBooks in stock for up to $120 off MSRP including free shipping plus NY & NJ sales tax only. For a limited time, Adorama will include a free Apple USB-C to USB Adapter,... Read more
15-inch 2.2GHz Retina MacBook Pro on sale for... has the 15″ 2.2GHz Retina MacBook Pro on sale for $1799 including free shipping. Their price is $200 off MSRP, and it’s the lowest price available for this model (except for Apple’s $1699... Read more
iPhone 6s and 6s Plus Feature Improved Durabi...
Upgraded components in the new iPhone 6s Plus cost $16 more than the components in the earlier iPhone 6 Plus according to a preliminary estimate from IHS Inc. The bill of materials (BOM) for an... Read more
13-inch Retina MacBook Pros on sale for up to...
Adorama has 13″ Retina MacBook Pros on sale for up to $130 off MSRP. Shipping is free, and Adorama charges sales tax for NY & NJ residents only: - 13″ 2.7GHz/128GB Retina MacBook Pro: $1199.99 $... Read more
Apple refurbished 2014 13-inch Retina MacBook...
Apple has Certified Refurbished 2014 13″ 2.6GHz/128GB SSD Retina MacBook Pros available $979, $320 off original MSRP. An Apple one-year warranty is included, and shipping is free: - 13″ 2.6GHz/128GB... Read more
iOS 9 Reflections Ten Days In – The ‘Book Mys...
I’ve never been much of an early adopter by philosophy or temperament, although I did buy the iPad Air 2 I’m typing this column on last fall only about a month after Apple unveiled it. However, my... Read more
Apple refurbished Time Capsules available for...
Apple has certified refurbished Time Capsules available for $120 off MSRP. Apple’s one-year warranty is included with each Time Capsule, and shipping is free: - 2TB Time Capsule: $179, $120 off - 3TB... Read more

Jobs Board

Senior Payments Security Manager - *Apple*...
**Job Summary** Apple , Inc. is looking for a highly motivated, innovative and hands-on senior payments security manager to join the Apple Pay security team. You will Read more
*Apple* Solutions Consultant - Retail Sales...
**Job Summary** As an Apple Solutions Consultant (ASC) you are the link between our customers and our products. Your role is to drive the Apple business in a retail Read more
*Apple* Site Security Manager - Apple (Unite...
**Job Summary** The Site Security Manager is a high-profile security position at Apple . The Site Manager is the face of Apple Global Security (GS) and primary point Read more
*Apple* Fulfillment Operations Execution Ana...
**Job Summary** The AMR Apple Fulfillment Operations Team is seeking a talented team player to drive the Apple Online Store (AOS) fulfillment performance to ensure a Read more
*Apple* Distinguished Educator (ADE) Communi...
**Job Summary** Apple is seeking candidates for a new position on the Apple Distinguished Educator (ADE) Program team as ADE Community Support Manager. Join a team Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.