1

Whilst programming in Objective-C I've occasionally had methods throw an exception that I wasn't expecting.

With the benefit of hindsight I can see why it would throw an exception and, often, addressing the issue leads to better code.

However, it would be handy to know, ahead of time, what methods will throw an exception and under what circumstances.

For example:

NSString *aString;
aString = @"Less than 42 characters.";
[aString substringToIndex:42];

would throw an exception as the string contains less than 42 characters.

Also this:

NSString *aString = @"This is a string.";
NSString *bString = nil; 
aString = [NSString stringByAppendingString:bString];

will similarly crash as bString is nil.

Any other examples?

Snowcrash
  • 80,579
  • 89
  • 266
  • 376
  • 1
    Not quite a dupe, but almost: http://stackoverflow.com/questions/4310560/usage-of-nsexception-in-iphone-apps Specifically: **Do not use exceptions to indicate anything but unrecoverable errors** (see that q/a for details -- bottom line: don't use exceptions for catching range errors) – bbum Apr 27 '11 at 15:06

2 Answers2

2

However, it would be handy to know, ahead of time, what methods will throw an exception and under what circumstances.

It tells you in the documentation.

kubi
  • 48,104
  • 19
  • 94
  • 118
  • 1
    If the implication is that you should rely on such exceptions in your parsing code, don't do that.... – bbum Apr 27 '11 at 15:07
1

While Objective-C does support exceptions, they are seldom used. The biggest issue with them are memory leaks that are caused by jumping out of the context before an object can be released (although that's no problem in a GC environment any more).

Exceptions are mostly used in fatal conditions in Objective-C, they are seldom used for recoverable errors. For that, methods pass pointers-to-pointers, as in +[NSURLConnection sendSynchronousRequest:returningResponse:error:].

So as long as the documentation doesn't say anything about exceptions explicitly, you don't need to care for them much.

Your first example will always throw an exception BTW, as NSString doesn't have a method subString:.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • Do not think that memory leaks are no longer a problem if you are using GC. Memory that is `malloc`ed and freed can still leak, so can CF objects and file descriptors. – JeremyP Apr 27 '11 at 14:28
  • @JeremyP: Right, overlooked that. GC is for sissies anyways ;-) – DarkDust Apr 27 '11 at 14:42
  • There are plenty of other reasons to not use exceptions, the biggest being that throwing an exception across a call into the frameworks is undefined behavior. BTW: The Mac OS X GC is actually faster than non-GC code in many common cases. Faster, smaller memory footprint, and less code for me to maintain? Yes, please. – bbum Apr 27 '11 at 15:05