Table of Contents Previous Section
Handling an Exception
Where and how an exception is handled depends on the context where the exception was raised. In general, a raise message is sent to an NSException object within the domain of an exception handler. An exception handler is contained within a control structure created by the keywords NS_DURING, NS_HANDLER, and NS_ENDHANDLER, as shown here:
.The section of code between NS_DURING and NS_HANDLER is the exception handling domain; the section between NS_HANDLER and NS_ENDHANDLER is the local exception handler. The normal flow of program execution is marked by the gray arrow; the code within the local exception handler is executed only if an exception is raised. Sending a raise message to an exception object causes program control to jump to the first executable line following NS_HANDLER.
.
NS_DURING
[some code];
[some more code];
NS_HANDLER
[exception handler code];
[more exception handler code];
NS_ENDHANDLER
.
.
Although an exception can be raised directly within the exception handling domain, exceptions more often arise indirectly from a method invoked from the domain. No matter how deep in a call sequence the exception is raised, execution jumps to the local exception handler (assuming there are no intervening exception handlers, as discussed in the next section). In this way, exceptions raised at a low level can be caught at a high level.
You may leave the exception handling domain (the section of code between NS_DURING and NS_HANDLER) by:
- Raising an exception.
- Calling NS_VALUERETURN(), which returns a value from the DURING block.
- Calling NS_VOIDRETURN, which returns void from the DURING block.
- "Falling off the end."
Note: You can't use return to exit an exception handling domain-errors will result.
Table of Contents Next Section