开发者

Handling exceptions in Objective-C

H开发者_如何学编程ow am I supposed to handle exceptions in Objective-C? I am getting an NSInvalidArgumentException while coding; using breakpoints, I can figure out where the exception is happening. I tried something like this:

@try{ 
  //My code
}
@catch(id e){

}

But it is not working.


In Cocoa, you should think of an exception as a crash with extra information (with rare exceptions <- ha!).

You don't want to handle an NSInvalidArgumentException exception. You want to understand why it happened and change your code such that it doesn't happen.


Go to the Run menu in XCode, an select Stop on Objective-C Exceptions. Now your code will stop at the place that's actually throwing the exception, so you can see exactly what line triggered it.


To catch an exception in objective-c you need to do this:

@try
{ 
  //Your code
}
@catch(NSException* e) // or subclass of NSException
{

}

However you do not want to catch an NSInvalidArgumentException, as it is indicative of a bug in your code. As Ken says, it's effectively a controlled crash. The most common cause of this exception is trying to insert nil into a colllection e.g. NSMutableArray or NSMutableDictionary. If that is the problem, you can find it really easily by running your code in the debugger with "Stop on Objective-C exceptions" enabled.


You should always strive to write code that will not generate exceptions. That said, you CAN handle exceptions on iOS. Read this blog st by Matt Gallagher: http://cocoawithlove.com/2010/05/handling-unhandled-exceptions-and.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜