views:

22

answers:

1

Hi,

I use asserts quite a bit in my code since they are useful in debugging, but the standard behaviour of Cocoa applications is to interrupt processing and logging the assertion failure to the console.. the UI stays up neither crashing, nor bringing up an error dialog and it's often not obvious what has happened.

What's the easiest way of either crashing the program (at least then you get a trace) or bringing up an error dialog?

Do I need to supply an assertion handler (that looks very complicated!)? or can I catch exceptions in the run loop are something?

Is there any example code available anywhere on how to best do this?

Thanks for your help.

+1  A: 

In answer to the subject of your question: You don't.

To crash immediately: abort();

To raise an error, simply create the NSError object, complete with description (for custom message, error number, etc.), and ask NSApp to -presentError:

I recommend you go the NSError route. Cocoa gives you a LOT of error handling and even error recovery capabilities. It's infinitely better to provide an error (and potentially recovery options for the user) than to simply crash. After all, if you know where an error is going to occur (enough to call abort() there) and you know what you're asserting (enough to user NSAssert), then you know enough about how either to recover automatically or to give options to the user so they can decide what to do.

Check out the Error Handling Programming Guide for details.

Joshua Nozzi
Hi Josh,Thanks for the info. I was thinking along the lines of "automatically" crashes / brings up an error dialog. In the cases, where I know it might crash there, I create an error log with debugging information, but this is for the totally unexpected cases where something is nil that shouldn't be etc.. I don't want to pollute my code with thousands of lines of error handling code, but I do want to be able to track unexpected problems with assertions. I guess there is no automatic way of making assertions crashing/ reporting?
Frank R.
I don't think it's possible to display any kind of error dialog once NSAssert has been hit. Again, though, if you *know* you could crash if a certain value isn't just right, guard it and present an error that gives the user a chance to correct (or make the value impossible to begin with). I have to heartily disagree that this is "pollution" in your code. This makes your overall app far more robust and leads to less support requests (because they're armed with what they need to know to try solving it themselves).
Joshua Nozzi