Re: Making failed NSAsserts crash an app
Re: Making failed NSAsserts crash an app
- Subject: Re: Making failed NSAsserts crash an app
- From: Keith Duncan <email@hidden>
- Date: Thu, 27 Aug 2009 22:28:55 +0100
They do not, check that, should not become less true just
because your app is built release vs debug.
Strictly speaking I believe you're more accurately describing an
invariant than an assertion.
Not all error states are fatal states. Assert happens when entering
an error state, and is left out of release. abort() happens when
entering a fatal state, and is kept in release (hopefully to never be
executed).
Instead of debating the meaning of assertion we should discuss the
specific implementation of Cocoa 'assertions', as found in the
NSException header. As observed by inspection they call methods on
NSAssertionHandler which are documented to raise an exception.
If you are using assertions to test for things that are handleable
situations or recoverable errors, you are doing it wrong. Checking
is good,
but its just that, checking... not asserting.
There's a difference between a condition that will cause your app to
crash and a condition that will cause your app to perform extra
work/graphics glitch/other easily fixed state. Obviously these latter
cases are not desirable, but they're not crashers.
On the basis of an exception causing your application to crash the
NSAssert family of assertions should only be used as shorthand for
throwing an NSException and in the situations where that is appropriate.
I'm pretty sure the reasons for throwing an exception have been
discussed on the list before and can be found in the archives.
So,
How can I guarantee that a failed NSAssert will crash my application?
Depending on where you fail an assertion (which will throw an
exception) either the uncaught exception handler or the NSApplication
handler will be called.
NSExceptions that originate on the main thread are caught by
NSApplication and printed to the system log. NSExceptions that occur
elsewhere are caught by the uncaught exception handler and will crash
your application. You can manipulate the uncaught exception handler
using NSSetUncaughtExceptionHandler.
If you want to do something other than simply log main thread
exceptions you can capture them by overriding -[NSApplication
reportException:] in a subclass or category. This is illustrated in
the cocoadev wiki http://www.cocoadev.com/index.pl?StackTraces
As you've duly noted NSAssert/NSException are for programmer error,
you've either done something wrong or received an unsuitable input.
Make sure to use NSError as appropriate too.
Keith
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden