0

I have a condition that should actually never happen, but if this does happen how does one deal with this in Objective-C?

In the java domain I would through a Runtime exception, which stops the program from executing. (I would still get a detailed stack trace and be able to determine the cause when debugging).

Objective-C does have exceptions, but from what I gather this is not the norm to use, one should rather use NSError in general.

Should one still use NSError for such cases or is there some other magic I can perform such as exit(1)?

I need something that is valid and will fly by Apple; What is the best ways to deal with this scenario?

Wayne
  • 3,359
  • 3
  • 30
  • 50
  • If you want to exit the app then raising an exception should be fine. You can also track it with crash reporting tools. – Aris May 12 '17 at 10:36
  • Take a look at this discussion: http://stackoverflow.com/questions/355168/proper-way-to-exit-iphone-application – Yuri Solodkin May 12 '17 at 10:48

1 Answers1

1

First, you should add assertions for many, if not all, of these cases so that they will be caught during development and fixed.

In production, the assertions will not be hit so you have two options, let the application crash or try to fail gracefully. Which of the two of these you choose depends on a ton of things. Can you fail gracefully? Does this put you in a really bad state if you can't?

This question can't be fully answered - it depends on the application, the use-case, the situation/circumstances. Maybe you just return early... Maybe you let it crash... Maybe you return an error and tell the user some useful message to fix it... I can't recommend anything without having a full understanding of your app and the thing that "should never happen".

Mike
  • 9,765
  • 5
  • 34
  • 59
  • The actual problem is how does one fail gracefully. I can think of presenting a dialog with an error message of some sort and (provide no way to dismiss this dialog). But even better would if I could display an error message and an OK which will terminate the application. – Wayne May 15 '17 at 11:03
  • The second very likely breaks apples guidelines. Again, failing gracefully completely depends on what you're talking about. Why are you in a state you can't recover from in the first place? – Mike May 15 '17 at 12:06
  • Imagine that Apple API changes is a bad way, and a callback with a state you are not anticipating, or some backend system returning a value you are not capable of dealing with. Here I guess one would rather be aware of some bad situation and if we get a crash one can fix it. – Wayne May 15 '17 at 12:36