Skip to main content

Exceptions – Try, Catch and Finally in iPhone Objective C

You won't find exceptions used as frequently in Objective-C as in other languages. However, try/catch/finally blocks can be useful to capture errors that may otherwise cause an app to fail.

In the example below, I allocate an array, however I don't add any elements to the array. Inside the try block the attempt to access the first element will cause an exception to be thrown.

NSArray* arraytest = [[NSArray alloc] init];
 
@try
{
// Attempt access to an empty array
NSLog(@"Object: %@", [arraytest objectAtIndex:0]);
 
}
@catch (NSException *exception)
{
// Print exception information
NSLog( @"NSException caught" );
NSLog( @"Name: %@", exception.name);
NSLog( @"Reason: %@", exception.reason );
return;
}
@finally
{
// Cleanup, in both success and fail cases
NSLog( @"In finally block");
 
[arraytest release];
}

The output of the code is shown below:

iPhoneApp[4464:b903] NSException caught
iPhoneApp[4464:b903] Name: NSRangeException
iPhoneApp[4464:b903] Reason: *** -[NSArray objectAtIndex:]: index 0 beyond bounds for empty array
iPhoneApp[4508:b903] In finally block

The @finally clause is called regardless of the outcome of the code the in @try block. This is the perfect place to perform any relevant code cleanup.

Using exceptions can be helpful when working with files (for exampleNSFileHandleOperationException), when working with data from unknown sources, etc.

Catching a Specific Exception

Using NSException as shown in the @catch statement above, will result in all exceptions being caught. You can also look for a specific exception – the code below looks only forNSRangeException:

@try
{
// Attempt access to an empty array
NSLog(@"Object: %@", [arraytest objectAtIndex:0]);
 
}
@catch (NSRangeException *exception)
{
// Print exception information
NSLog( @"NSRangeException caught" );
NSLog( @"Reason: %@", exception.reason );
return;
}
@finally
{
// Cleanup, in both success and fail cases
NSLog( @"In finally block");
 
[arraytest release];
}

Throwing an Exception

You can also throw an exception in your own code. Although a bit contrived (as a means to get the point across), the method testException() shown below will throw an exception whenever it is called:

- (void)testException
{
if (1 == 1)
{
NSException *exception = [NSException exceptionWithName: @"Exception!"
reason: @"Something not so good occurred."
userInfo: nil];
@throw exception;
}
}

Further along in the code, when testException() is called, wrap the invocation in a try/catch/finally blocks in a manner similar to what was shown above:

@try

{
// Call the method...
[self testException];
}
@catch (NSException *exception)
{
// Print exception information
NSLog( @"NSException caught" );
NSLog( @"Name: %@", exception.name);
NSLog( @"Reason: %@", exception.reason );
return;
}
@finally
{
NSLog( @"In finally block");
}

iPhoneApp[4660:b903] NSException caught
iPhoneApp[4660:b903] Name: Exception!
iPhoneApp[4660:b903] Reason: Something not so good occurred.
iPhoneApp[4660:b903] In finally blockI guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.

[iPhone Development][iOS Development][xCode][iPhone][iPad][Objective C]

Popular posts from this blog

Nested Collection Models in MVC to Add Multiple Phone Numbers - Part 3

This is Part 3 of the article series. Actually, in this article series we were developing an MVC application that will allow adding multiple phone numbers using Nested Model concept. User will be able to add or remove (zero or more phone numbers, I need minimum two phone numbers for each employee) phone numbers for any single employee. Previous logs: Nested Collection Models in MVC to Add
✔ Read More...
I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address t…

iPhone Application for Islamic Duas

Islamic Duas is an app designed for Muslims around the world who don’t get the time to go through Islamic books and are looking for authentic duas to pray. This app is a solution to all your needs as every Muslim knows that a prayer in time can save you from a lot of trouble. This app carries important Islamic duas for different occasions, daily life events and end of prayer duas to seek forgiveness from Allah etc. These Islamic duas are collected from authentic sources and are very beneficial in life of a Muslim. The app is available for free for iOS and Android users. Use the following buttons to download the ap. 

Download from here:

Muslim Some of the Islamic duas included in Muslim Dua Now are: Duas for dressing/undressing/new clothesDuas for entering and leaving restroomDuas Before and After AblutionDuas for hearing AdhanDuas for Entering and leaving mosqueDua against distraction from ShaytanDuas for protection from evilDuas before and after eatingDuas to recite when fearing harm fro…

HTML5 and CSS3 Zebra Striping - Look Ma No JavaScript

It was 5 maybe 6 years ago when I first started learning jQuery. One of the first things I did was order the jQuery In Action book. If you have read that book you should remember one of the first examples given, zebra striping a table. To me this example sold me on the idea of jQuery even if I did not actually understand how jQuery worked at the time. With one line of code I could now alternate background colors in a table.
✔ Read More...
I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too.

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. W…