Table of Contents Previous Next
Logo
Client-Side Slice-to-Objective-C Mapping : 18.13 Exception Handling
Copyright © 2003-2009 ZeroC, Inc.

18.13 Exception Handling

Any operation invocation may throw a run-time exception (see Section 18.10.4 on page 535) and, if the operation has an exception specification, may also throw user exceptions (see Section 18.10 on page 530). Suppose we have the following simple interface:
exception Tantrum {
    string reason;
};

interface Child {
    void askToCleanUp() throws Tantrum;
};
Slice exceptions are thrown as Objective‑C exceptions, so you can simply enclose one or more operation invocations in a trycatch block:
id<EXChildPrx> child = ...;    // Get proxy...
@try {
    [child askToCleanUp];      // Give it a try...
} @catch (EXTantrum *t) {
    printf("The child says: %s\n", t.reason_);
}
Typically, you will catch only a few exceptions of specific interest around an operation invocation; other exceptions, such as unexpected run-time errors, will typically be dealt with by exception handlers higher in the hierarchy. For example:
void run()
{
    id<EXChildPrx> child = ...;       // Get proxy...
    @try {
        [child askToCleanUp];         // Give it a try...
    } @catch (EXTantrum *t) {
        printf("The child says: %s\n", t.reason);
        [child scold];                // Recover from error...
    }
    [child praise];                   // Give positive feedback...
}

int
main(int argc, char* argv[])
{
    int status = 1;
    @try {
        // ...
        run();
        // ...
        status = 0;
    } @catch (ICEException *e) {
        printf("Unexpected runtime error: %s\n", [e ice_name]);
    }
    // ...
    return status;
}
This code handles a specific exception of local interest at the point of call and deals with other exceptions generically. (This is also the strategy we used for our first simple application in Chapter 3.)

Exceptions and Out-Parameters

If an operation throws an exception, the Ice run time makes no guarantee for the value of out-parameters. Individual out-parameters may have the old value, the new value, or a value that is indeterminate, such that parts of the out-parameter have been assigned and others have not. However, no matter what their state, the values will be "safe" for memory-management purposes, that is, any out-parameters that were successfully unmarshaled are autoreleased.

Exceptions and Return Values

For return values, the Objective‑C mapping provides the guarantee that a variable receiving the return value of an operation will not be overwritten if an exception is thrown.
Table of Contents Previous Next
Logo