6

When working on a Swift library for iOS, you would you sandbox the library so an error in this library will not be repercuted in the host application? (= uncaught error will not crash the app)

Here are some clue that don't cover everything perfectly:

  • using NSSetUncaughtExceptionHandler: only catch Obj-c exception (NSException)
  • using background queue with try/catch and closure, such as here.

The disered behavior can compare to Android where you could have one Thread and have an Thread.UncaughtExceptionHandler on it so everything going wrong here will be catched.

There may be no proper solution except try/catching everything because of the design of the language (see here).

Hugo Gresse
  • 17,195
  • 9
  • 77
  • 119

1 Answers1

6

Generally, in iOS you will throw an exception for situations where it is no longer safe to continue. For example, if the host application passing along bad initialization data to your library you should crash as it's undefined behavior to continue running.

As it turns out, crashing is only the third worst thing that you can do and as such you should do it rather than either of the two worse things.

Worst Things:

  1. Corrupt user data
  2. Hard to diagnose issues (undefined behavior, inconsistent behavior, etc)
  3. Crash

It's perfectly fine to either crash, or use throws for methods which can fail, return nil, or return an Error object in a callback.

Steven Hepting
  • 12,394
  • 8
  • 40
  • 50