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

Cleaning up with @try / @catch / @finally

This lesson covers cleanup with @try, @catch, and @finally in Objective-C, with the aim of running something whether or not an exception occurred.

A @finally block always runs, exception or no exception. Use it to close a file or to signal that work has finished.

In the sample code, divide() raises a division-by-zero error with @throw and catches it with @catch. The @finally block always shows "Ending the calculation", error or not.

A common early stumble is that Objective-C does not use exceptions very often. iOS convention handles most errors through NSError, so @finally is not an especially common construct either.

In professional work, exceptions are used in limited situations such as detecting fatal bugs, while ordinary errors go through NSError.

๐Ÿ“– 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)