Who Should Read This Document?
Organization of This Document
See Also
This document discusses how to raise and handle exceptions: special conditions that interrupt the normal flow of program execution.
Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime.
If you have an existing body of code (such as third-party library) that uses exceptions to handle error conditions, you may use the code as-is in your Cocoa application. But you should ensure that any expected runtime exceptions do not escape from these subsystems and end up in the caller’s code. For example, a parsing library might use exceptions internally to indicate problems and enable a quick exit from a parsing state that could be deeply recursive; however, you should take care to catch such exceptions at the top level of the library and translate them into an appropriate return code or state.
Instead of exceptions, error objects (NSError
) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications. For further information, see Error Handling Programming Guide For Cocoa.
This document describes how to raise and handle exceptions in Objective-C. For exceptions in Java, use the exception mechanism provided by java.lang.Throwable
and subclasses of java.lang.Exception
. The NSException class is also available in Java as a subclass of java.lang.RuntimeException
; exceptions raised by the Objective-C portion of Cocoa are converted to this class when received by Java.
This document contains the following articles:
“Predefined Exceptions” describes where to find exceptions defined by Cocoa.
“Uncaught Exceptions” describes what happens to an exception not caught by an exception handler.
“Handling Exceptions” describes how to handle an exception using the compiler directives @try
, @catch
, and @finally
and the legacy macros NS_DURING
, NS_HANDLER
, and NS_ENDHANDLER
..
“Throwing Exceptions” describes how to throw (raise) an exception.
“Nesting Exception Handlers” describes how exception handlers can be nested.
“Controlling a Program’s Response to Exceptions” describes how to use the Exception Handling framework for monitoring and controlling the behavior of Cocoa programs in response to various types of exceptions.
For information on originating, handling, and recovering from expected runtime errors, see Error Handling Programming Guide For Cocoa. Also see the related document,Assertions and Logging, for information on the Foundation framework's support for making assertions and logging error information.
© 2002, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-10-02)