Exceptions
Objective-C has exceptions with @try, @catch, @finally and @throw, much like Java. But Cocoa uses them very differently: an NSException signals a programmer error (a bug), not a normal failure. Recoverable problems use NSError (previous lesson); an uncaught exception terminates the app.
Exceptions Foundation raises
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSArray *items = @[@"a", @"b", @"c"];
@try {
NSLog(@"about to read index 5");
id x = items[5]; // out of range
NSLog(@"never printed: %@", x);
} @catch (NSException *e) {
NSLog(@"caught %@", e.name);
NSLog(@"reason: %@", e.reason);
} @finally {
NSLog(@"finally always runs");
}
@try {
NSMutableDictionary *d = [NSMutableDictionary dictionary];
id missing = nil;
[d setObject:missing forKey:@"key"]; // nil value
} @catch (NSException *e) {
NSLog(@"caught %@", e.name);
}
NSLog(@"program continues");
}
return 0;
}about to read index 5
caught NSRangeException
reason: Index 5 is out of range 3 (in 'objectAtIndex:')
finally always runs
caught NSInvalidArgumentException
program continues
The reason text differs between Apple's Foundation and GNUstep, but the exception names are the same, so code should test e.name, never parse the reason.
| Name | Typical cause |
|---|---|
NSRangeException |
index or range outside a collection or string |
NSInvalidArgumentException |
nil where an object is required, unrecognized selector |
NSInternalInconsistencyException |
an object reached an impossible state (failed assertion) |
NSUnknownKeyException |
KVC with a key that doesn't exist |
NSGenericException |
mutating a collection while enumerating it, among others |
Raising your own
Use [NSException raise:format:] or @throw to stop on a broken precondition:
#import <Foundation/Foundation.h>
@interface Matrix : NSObject
@property (nonatomic, readonly) NSInteger rows, cols;
- (instancetype)initWithRows:(NSInteger)rows cols:(NSInteger)cols;
@end
@implementation Matrix
- (instancetype)initWithRows:(NSInteger)rows cols:(NSInteger)cols {
if (rows <= 0 || cols <= 0) {
[NSException raise:NSInvalidArgumentException
format:@"Matrix size must be positive, got %ldx%ld", (long)rows, (long)cols];
}
self = [super init];
if (self) { _rows = rows; _cols = cols; }
return self;
}
@end
int main(void) {
@autoreleasepool {
Matrix *ok = [[Matrix alloc] initWithRows:2 cols:3];
NSLog(@"created %ldx%ld", (long)ok.rows, (long)ok.cols);
@try {
(void)[[Matrix alloc] initWithRows:0 cols:3]; // (void): we only want the exception
} @catch (NSException *e) {
NSLog(@"%@: %@", e.name, e.reason);
}
@try {
@throw [NSException exceptionWithName:@"QuotaExceeded"
reason:@"Only 3 projects on the free plan"
userInfo:@{@"limit": @3}];
} @catch (NSException *e) {
NSLog(@"%@ (limit %@)", e.reason, e.userInfo[@"limit"]);
}
}
return 0;
}created 2x3
NSInvalidArgumentException: Matrix size must be positive, got 0x3
Only 3 projects on the free plan (limit 3)
Catching selectively and rethrowing
Several @catch blocks are tried in order. Inside a @catch, a bare @throw; rethrows the current exception to an outer handler:
#import <Foundation/Foundation.h>
void riskyStep(NSInteger step) {
if (step == 1) {
[NSException raise:NSRangeException format:@"step %ld out of range", (long)step];
} else if (step == 2) {
[NSException raise:NSInternalInconsistencyException format:@"bad state at step %ld", (long)step];
}
NSLog(@"step %ld ok", (long)step);
}
void runStep(NSInteger step) {
@try {
riskyStep(step);
} @catch (NSException *e) {
if ([e.name isEqualToString:NSRangeException]) {
NSLog(@"recovered from range problem: %@", e.reason);
} else {
NSLog(@"can't handle %@ here, rethrowing", e.name);
@throw;
}
} @finally {
NSLog(@"cleanup after step %ld", (long)step);
}
}
int main(void) {
@autoreleasepool {
for (NSInteger step = 0; step < 3; step++) {
@try {
runStep(step);
} @catch (NSException *e) {
NSLog(@"top level caught: %@", e.reason);
}
}
}
return 0;
}step 0 ok
cleanup after step 0
recovered from range problem: step 1 out of range
cleanup after step 1
can't handle NSInternalInconsistencyException here, rethrowing
cleanup after step 2
top level caught: bad state at step 2
@finally runs whether the block finished normally, was caught, or the exception was rethrown.
Assertions
NSAssert and NSParameterAssert check assumptions during development; a failed assertion first logs where it happened (through NSAssertionHandler; the exact wording differs between platforms) and then raises NSInternalInconsistencyException. Release builds usually compile them out with NS_BLOCK_ASSERTIONS.
#import <Foundation/Foundation.h>
double safeDivide(double a, double b) {
NSCParameterAssert(b != 0); // the C-function version of NSParameterAssert
return a / b;
}
int main(void) {
@autoreleasepool {
NSLog(@"%.2f", safeDivide(10, 4));
@try {
safeDivide(1, 0);
} @catch (NSException *e) {
NSLog(@"assertion failed: %@", e.name);
}
}
return 0;
}2.50
/w/main.m:4 Assertion failed in double safeDivide(double, double). Invalid parameter not satisfying: b != 0
assertion failed: NSInternalInconsistencyException
Why not use exceptions for normal errors?
- Under ARC, code is not exception-safe by default: objects alive in the frames an exception unwinds through can leak.
- Apple's frameworks are not designed to have exceptions thrown through them, so the app's state may be inconsistent afterwards.
- Swift can't catch
NSExceptionat all.
Note: The rule: let exceptions crash during development so you find the bug, and use
NSErrorfor anything that can legitimately go wrong at run time. Catching exceptions is fine at very narrow boundaries, such as calling a third-party library or showing the examples in this lesson.
Test yourself
In Cocoa, what are exceptions meant for?
- Every kind of failure
- Programmer errors (bugs)
- Network errors
- User input validation
What does @throw; (without an argument) do inside a @catch block?
- Nothing
- Rethrows the current exception
- Throws nil
- Ends the program immediately
When does a @finally block run?
- Only if no exception occurred
- Only if an exception was caught
- Always when leaving the @try statement
- Never under ARC