Sat
Sat

Reputation: 1626

Handling exceptions in Objective-C

How 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.

Upvotes: 1

Views: 299

Answers (4)

JeremyP
JeremyP

Reputation: 86651

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.

Upvotes: 1

Moshe
Moshe

Reputation: 58067

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

Upvotes: 1

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.

Upvotes: 3

Ken
Ken

Reputation: 13003

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.

Upvotes: 3

Related Questions