3

Is there a simple way of throwing the exception generated by an NSAssert when the condition is false? To draw a parallel of what I'm asking for: In C stdlib a failed assert results in a printf() and abort(). And in Java, a failed assert results in a java.lang.AssertionError. In ObjectiveC a failed assert seems to result in (copied from NSException.h):

[[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd
    object:self file:[NSString stringWithUTF8String:__FILE__]
        lineNumber:__LINE__ description:(desc), ##__VA_ARGS__];

The best equivalent I can think of is either putting the above block in a macro I define (let's call it NSFail()), or using NSAssert(NO, ...). The NSFail macro is a little undesirable since it seems like I'm defining something that essentially already exists. The NSAssert(NO,...) option is undesirable because I don't want the code disabled when NS_BLOCK_ASSERTIONS is defined.

ɲeuroburɳ
  • 6,990
  • 3
  • 24
  • 22
  • 2
    You can `abort()` in Objective-C too. Or `[[NSException new] throw]`. –  Sep 17 '13 at 16:43
  • If you like `assert` you can also use it. Note that the `assert`macro will expand to "void" when `NDEBUG` is defined, while `NSAssert` and friends will expand to nothing when `NS_BLOCK_ASSERTIONS` is defined. In Objective-C exceptions do not have much of a value, you SHALL abort as soon as possible, in this case. – CouchDeveloper Sep 17 '13 at 17:38

1 Answers1

0

Quick and dirty:

[[NSException new] raise]

You can also add descriptive reasons:

[[NSException exceptionWithName:@"Impossible" reason:@"Something happened that was not supposed to" userInfo:nil] raise]

NSException apple docs

Brenden
  • 7,708
  • 11
  • 61
  • 75