Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 10 / 68

Error handling (@try / @catch)

This lesson covers error handling with @try and @catch in Objective-C, with the aim of keeping a program running even when something unexpected goes wrong.

@try / @catch catches an error (an exception) so the whole program does not stop. Think of it as insurance: deciding in advance what to do instead, should something fail.

The sample code reaches past the end of an array inside a @try block and catches the exception with @catch (NSException *exception). Note how exception.reason pulls the reason out.

A common early stumble is that Objective-C does not use exceptions very often. iOS convention handles most errors through a separate mechanism, NSError, with exceptions reserved mainly for detecting bugs.

In professional work, the usual split is exceptions for fatal bugs and NSError for ordinary failures such as a network error.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)