1

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.

2
  • paste the actual error message into your question. Commented Dec 7, 2010 at 5:34
  • 1
    I've rewritten your question to resemble English, but I hope that I have preserved your initial point. Let me know if I've messed something up. Cheers! Commented Dec 7, 2010 at 6:23

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.