NSError vs. NSException
Objective-C draws a firm line between two different failure-handling mechanisms that are frequently confused. NSException, raised with @throw and caught with @try/@catch/@finally, is reserved for programmer errors — bugs like accessing an array index out of bounds, sending an unrecognized selector, or force-unwrapping something that violates a precondition — errors that should ideally crash in development and get fixed, not be routinely recovered from in production code. NSError, by contrast, is Foundation's convention for recoverable, expected failure conditions — a file that doesn't exist, a network request that times out, JSON that fails to parse — situations a well-behaved app is expected to handle gracefully and continue running. This is why almost every Foundation and UIKit API that can fail for ordinary reasons (like NSFileManager or NSJSONSerialization) takes an NSError ** out-parameter instead of throwing an exception, while exceptions are reserved for genuinely exceptional, unrecoverable programming mistakes.
Cricket analogy: NSException is like a match getting abandoned entirely because of a serious rule violation such as ball tampering — a rare, exceptional event that halts play; NSError is like a routine rain delay, an expected condition the match officials have a standard, non-catastrophic procedure to handle and resume from.
Producing and Consuming NSError
The idiomatic method signature for a failable operation is - (BOOL)doSomethingWithError:(NSError **)error (or a nullable object return that's nil on failure), and the caller passes the address of a local NSError pointer, initialized to nil: NSError *error = nil; then [obj doSomethingWithError:&error];. Crucially, the return value (BOOL or a nil object) is the authoritative signal of success or failure — you must always check it first, because a well-behaved method is only obligated to populate the error pointer when it actually fails; checking only 'if (error)' without checking the return value is a documented anti-pattern, since some methods may leave stale garbage in an uninitialized error variable or the caller might reuse the same NSError * across multiple calls. An NSError itself bundles a domain (a namespacing string, often a class-specific constant like NSCocoaErrorDomain), a code (an integer meaningful within that domain), and a userInfo dictionary that commonly contains NSLocalizedDescriptionKey for a human-readable message and NSUnderlyingErrorKey to chain a lower-level cause.
Cricket analogy: Checking the BOOL return value first, not just the error pointer, is like trusting the umpire's raised finger for a dismissal as the authoritative signal rather than assuming a batter is out just because there was an appeal — the appeal (error pointer) alone doesn't mean the wicket actually fell.
- (BOOL)loadConfigFromPath:(NSString *)path error:(NSError **)error {
NSData *data = [NSData dataWithContentsOfFile:path options:0 error:error];
if (!data) {
return NO; // 'error' was already populated by dataWithContentsOfFile:options:error:
}
NSError *jsonError = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (!json) {
if (error) {
*error = [NSError errorWithDomain:@"com.myapp.config"
code:1001
userInfo:@{
NSLocalizedDescriptionKey: @"Config file is not valid JSON",
NSUnderlyingErrorKey: jsonError
}];
}
return NO;
}
// ... use json ...
return YES;
}
// Caller:
NSError *loadError = nil;
BOOL success = [self loadConfigFromPath:@"config.json" error:&loadError];
if (!success) {
NSLog(@"Failed to load config: %@", loadError.localizedDescription);
}Custom Error Domains and Recovery
Well-designed libraries define their own error domain as a string constant (typically reverse-DNS style, e.g., static NSString *const MyAppNetworkErrorDomain = @"com.myapp.network";) and an accompanying NS_ENUM of error codes, so callers can write robust handling logic like if ([error.domain isEqualToString:MyAppNetworkErrorDomain] && error.code == MyAppNetworkErrorTimeout) rather than fragile string-matching against localizedDescription, which is meant only for display and can change with localization or wording tweaks. For errors that offer the user an actual recovery path, NSError's userInfo can include NSLocalizedRecoverySuggestionKey (a suggested next step) and NSLocalizedRecoveryOptionsKey paired with a recovery attempter object implementing attemptRecoveryFromError:optionIndex: — this is how AppKit's document-based error recovery UI (offering buttons like 'Try Again' or 'Save a Copy') is implemented, though it's used far less often on iOS, where apps typically just present the localizedDescription in a UIAlertController and let the user retry manually.
Cricket analogy: Matching on error.domain and error.code instead of the display string is like an umpire's official decision review relying on ball-tracking data and snickometer readings rather than just listening to the commentator's spoken description of what happened, which can vary in wording each time.
Never use @try/@catch to handle NSError-style recoverable failures, and never rely on NSError for genuine programmer bugs. Catching NSException around ordinary operations (like a failed network request) masks real bugs and adds overhead, since Objective-C exception handling isn't zero-cost the way it is in some other languages — @try blocks disable certain compiler optimizations around them even when no exception is thrown.
- NSException (via @throw/@try/@catch) is for programmer errors that should be fixed, not routinely handled; NSError is for expected, recoverable failures.
- The idiomatic pattern passes an NSError ** out-parameter, initialized to nil by the caller, and the method's return value (BOOL or nilable object) is the authoritative success/failure signal.
- Always check the return value first — a method is only obligated to populate the error pointer on failure, so checking 'if (error)' alone is an anti-pattern.
- NSError bundles a domain (namespace), a code (integer meaningful within that domain), and a userInfo dictionary (commonly NSLocalizedDescriptionKey and NSUnderlyingErrorKey).
- Custom libraries should define their own error domain constant and an NS_ENUM of codes so callers can match programmatically instead of string-matching localizedDescription.
- NSLocalizedRecoverySuggestionKey/NSLocalizedRecoveryOptionsKey enable structured error recovery UI, though iOS apps more commonly just present localizedDescription in an alert.
- @try/@catch has real runtime and optimization costs in Objective-C and should never be used as a substitute for NSError-based error handling.
Practice what you learned
1. What is the primary distinction between NSException and NSError in Objective-C convention?
2. When calling a method with an NSError ** parameter, what should you check first to determine success or failure?
3. What three pieces of information does an NSError object bundle together?
4. Why should error-handling code branch on error.domain and error.code rather than parsing error.localizedDescription?
5. Why is @try/@catch inappropriate for handling an ordinary failed network request?
Was this page helpful?
You May Also Like
ARC and Memory Management
How Automatic Reference Counting manages object lifetimes in Objective-C, and how it relates to the manual retain/release model it replaced.
Strong, Weak, and Retain Cycles
A deep look at how strong and weak references interact under ARC, and practical patterns for detecting and breaking retain cycles.
NSString and String Handling
How Objective-C represents and manipulates text with NSString and NSMutableString, including encoding, formatting, and common gotchas.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics