Panic in Objective-C

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // We'll use @throw throughout this site to check for
        // unexpected errors. This is the only program on the
        // site designed to throw an exception.
        @throw [NSException exceptionWithName:@"CustomException"
                                       reason:@"a problem"
                                     userInfo:nil];
        
        // A common use of @throw is to abort if a function
        // returns an error value that we don't know how to
        // (or want to) handle. Here's an example of
        // throwing an exception if we get an unexpected error when creating a new file.
        NSError *error;
        BOOL success = [@"Hello, World!" writeToFile:@"/tmp/file"
                                          atomically:YES
                                            encoding:NSUTF8StringEncoding
                                               error:&error];
        if (!success) {
            @throw error;
        }
    }
    return 0;
}

In Objective-C, we use exceptions for handling unexpected errors, which is similar to the concept of panic in other languages. The @throw directive is used to raise an exception.

Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.

When the first @throw in main fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first @throw.

$ gcc -framework Foundation example.m -o example
$ ./example
2023-05-24 10:15:30.123 example[1234:5678] *** Terminating app due to uncaught exception 'CustomException', reason: 'a problem'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff203bbb1e __exceptionPreprocess + 242
    1   libobjc.A.dylib                     0x00007fff20164bc4 objc_exception_throw + 48
    2   example                             0x000000010000f3e4 main + 116
    3   libdyld.dylib                       0x00007fff203a4621 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
Abort trap: 6

Note that unlike some languages which use exceptions for handling of many errors, in Objective-C it is common to use error-indicating return values (like NSError) wherever possible, and use exceptions for truly exceptional circumstances.

[Next Example: Deferred Execution]