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?
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.
- stringbyAppendingString
- substringToIndex
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:
.
精彩评论