0

Noting the general guidance re use of exceptions in objective-c (e.g. throwing an exception in objective-c/cocoa) I'm still not quite sure for this case:

is throwing an exception in an objective-c method when a required input parameter is nil best practice/ok?

If no, what approach would be typical then here in objective-c?

Community
  • 1
  • 1
Greg
  • 34,042
  • 79
  • 253
  • 454

2 Answers2

1

That would be a valid exception, or even an assert (which in turn will throw an exception). there is the NSParameterAssert macro defined already that will do what you want.

Joshua Weinberg
  • 28,598
  • 2
  • 97
  • 90
  • Joshua - will there be an exception in production however with assert? (just noted that @saury was suggested NSAsserts don't bet compiled into a release build) – Greg Oct 19 '11 at 05:46
  • Yes, NSAsserts still exist in Release code. They aren't compiled out. – Joshua Weinberg Oct 19 '11 at 12:34
1

An NSAssert is something which is more meant for the developers own convenience. Developers use it for checking the assumptions/conditions etc. One thing to note is that NSAssert will not be compiled into your code in a release build.

You do @throw NSException for your situation as they are meant only for these situations when you want to handle the cases for invalid inputs to your code at runtime.

NSErrors is also another facility provided by Apple. Its generally used for unwanted conditions which are not programming errors (say bluetooth hardware is defected and you bluetooth related application is dependent on that)

Saurabh
  • 7,894
  • 2
  • 23
  • 31
  • You should _never_ use exceptions for invalid user input. Exceptions are there for bugs in your code. The intention is not that you catch an exception, but that you find the bug in your code and fix it. Like the "parameter was required but is nil" - that's a bug in the caller's code, so the proper thing is to throw an exception, and if it ever happens, fix the caller of the method. NSError is for errors outside the control of the application (bad user input, server problems etc. ) – gnasher729 Mar 24 '14 at 12:42