19

I know there is an UncaughtExceptionHandler in Cocoa, However I am looking for same thing for Swift. i.e. whenever there is any error/exception in application which is not caught locally there due to any mistake, it should bubble all the way to the top level application object where I should be able to gracefully handle it and respond to user appropriately.

Android has it. Flex has it. Java has it. Wondering why Swift is missing this key feature.

Community
  • 1
  • 1
Sunny Tambi
  • 2,393
  • 3
  • 23
  • 27
  • 1
    NSSetUncaughtExceptionHandler is available is Swift: http://stackoverflow.com/questions/25441302/how-should-i-use-nssetuncaughtexceptionhandler-in-swift. However, it catches only Objective-C exceptions, not Swift runtime errors or `throw`n errors. – Martin R Aug 03 '16 at 08:14
  • 1
    Thanks @MartinR for your quick reply. I know about NSSetUncaughtExceptionHandler that it handles Objective-C exceptions. However I am looking for same/similar thing for Swift. – Sunny Tambi Aug 03 '16 at 08:19
  • Swift has no mechanism to catch all kind of runtime errors. I can only guess about the reason. For example it wouldn't work well with automatic reference counting. You may be able to get a better response from the Swift developers on one of the mailing lists at swift.org. – Martin R Aug 03 '16 at 08:20
  • Thanks again @MartinR... Do you know if event/exceptions/errors go through tunneling & bubbling phases in Swift .. I am just thinking if exceptions go through tunneling or bubbling phases, i could catch an exception at application level AppDelegate. – Sunny Tambi Aug 03 '16 at 08:28
  • @SunnyTambi Nice question have you got any workaround ? – Jack May 16 '18 at 06:24

2 Answers2

19

Swift has no mechanism to catch all arbitrary runtime exceptions. The reasons are explained in

in the swift-users forum. Extract:

Swift made a conscious choice not to include exceptions thrown through arbitrary stack frames not because it was technically impossible, but because its designers judged the costs to be too high.

The problem is this: if a piece of code is going to exit early because of an error, it has to be written to handle that early exit. Otherwise it will misbehave—fail to deallocate memory, fail to close file handles/sockets/database connections/whatever, fail to release locks, etc. In a language like Java, writing truly exception-safe code requires a ridiculous quantity of try/finally blocks. That's why nobody does it. They make judgements about which exceptions they're likely to see and which resources are dangerous to leak, and only protect their code against those specific anticipated conditions. Then something unforeseen happens and their program breaks.

This is even worse in a reference-counted language like Swift because correctly balancing the reference counts in the presence of exceptions basically requires every function to include an implicit finally block to balance all the retain counts. This means the compiler has to generate lots of extra code on the off chance that some call or another throws an exception. The vast majority of this code is never, ever used, but it has to be there, bloating the process.

Because of these problems, Swift chose not to support traditional exceptions; instead, it only allows you to throw errors in specially-marked regions of code. But as a corollary, that means that, if something goes really wrong in code that can't throw, all it can really do to prevent a disaster is crash. And currently, the only thing you can crash is the entire process.

For more information, see

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 3
    Thanks @MartinR ... I found that Swift guys has offloaded the burden of handling every single small or big exception and error to the developers "by design". – Sunny Tambi Aug 05 '16 at 04:52
  • 1
    Thanks so much for sharing, now at least the rationale is clear for what seemed like a puzzling omission. – Crashalot Oct 14 '16 at 04:59
  • 3
    This is fine with me, but I still need to at least be able to catch the signals so that I can implement my crash logger. Can't seem to make it work though; force unwrapping nil throws an `EXC_BAD_INSTRUCTION` that I'm unable to catch with either exception or signal handlers... – Nicolas Miari Nov 17 '16 at 01:48
18

This is the code I use to log all exceptions/errors. Log.error(with:) is a custom function where I store the stack trace, along with other info. Thread.callStackSymbols is an array of strings and represents the stack trace.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {

    NSSetUncaughtExceptionHandler { exception in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGABRT) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGILL) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGSEGV) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGFPE) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGBUS) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    signal(SIGPIPE) { _ in
        Log.error(with: Thread.callStackSymbols)
    }

    return true
}
Mark A. Donohoe
  • 28,442
  • 25
  • 137
  • 286
andrei
  • 1,353
  • 15
  • 24