Recover in Objective-C
#import <Foundation/Foundation.h>
// This function throws an exception.
void mayThrow() {
@throw [NSException exceptionWithName:@"SomeException"
reason:@"a problem"
userInfo:nil];
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
// In Objective-C, we use @try, @catch, and @finally for exception handling.
@try {
mayThrow();
// This code will not run, because mayThrow() throws an exception.
// The execution of main stops at the point of the exception
// and jumps to the @catch block.
NSLog(@"After mayThrow()");
} @catch (NSException *exception) {
// The @catch block is equivalent to recover() in Go.
// It catches the thrown exception and allows the program to continue.
NSLog(@"Caught exception. Error:\n %@", [exception reason]);
} @finally {
// The @finally block always executes, whether an exception was thrown or not.
NSLog(@"Cleaning up...");
}
}
return 0;
}
In Objective-C, we use exception handling mechanisms to recover from runtime errors, which is similar to recovering from panics in other languages. Here’s how it works:
We define a function
mayThrow()
that throws an exception. This is similar to themayPanic()
function in the original example.In the
main()
function, we use an@try
-@catch
-@finally
block to handle potential exceptions:- The
@try
block contains the code that might throw an exception. - The
@catch
block catches any thrown exceptions. This is equivalent to therecover()
functionality in the original example. - The
@finally
block (optional) contains code that will be executed whether an exception was thrown or not.
- The
If
mayThrow()
throws an exception, the execution immediately jumps to the@catch
block, skipping any code after the throw in the@try
block.In the
@catch
block, we can examine the caught exception and handle it appropriately. In this case, we’re just printing the error message.
To run this program:
Save the code in a file with a
.m
extension (e.g.,ExceptionHandling.m
).Compile it using the Objective-C compiler:
$ clang -framework Foundation ExceptionHandling.m -o ExceptionHandling
Run the compiled program:
$ ./ExceptionHandling Caught exception. Error: a problem Cleaning up...
This example demonstrates how Objective-C handles exceptions, which is conceptually similar to recovering from panics in other languages. It allows your program to gracefully handle runtime errors and continue execution when possible.