4

I have read in other threads, like this one, that throwing an exception in a language like c++ should be something that you only do in genuinely exceptional circumstances because the compiler is working as hard as it can to make the code run as fast as possible in the non-exception case and then pays the price for this speed by having expensive exception cases. Is this what happens in Swift too?

Swift developers seem generally comfortable throwing exceptions and I am wondering if I should try to avoid using the do-try-catch pattern.

rpecka
  • 1,168
  • 5
  • 17
  • 5
    Related: [Swift vs Obj-C exceptions. What is stack unwinding? Why doesn't Swift do it?](https://stackoverflow.com/questions/36423471/swift-vs-obj-c-exceptions-what-is-stack-unwinding-why-doesnt-swift-do-it) and [Error handling in Swift does not involve stack unwinding. What does it mean?](https://stackoverflow.com/questions/46814233/error-handling-in-swift-does-not-involve-stack-unwinding-what-does-it-mean) – rmaddy Apr 18 '19 at 20:18
  • 1
    Okay, both of those say that it's similar to a `return` statement, which is exactly what would happen anyway if you handled the error yourself and then left the scope so it seems like there is no additional cost. Interesting. – rpecka Apr 18 '19 at 20:23

2 Answers2

8

Think of throw and catch in Swift as merely a safe, controlled form of goto or jump. It's safe and controlled because the compiler sees to it that you cannot throw unless there is someone there to catch. What will happen under what circumstances is thus completely known at compile time.

That is totally different from Objc exceptions where nothing is known in advance, and at runtime we just start walking blindly up the call stack introspecting at every step, and ending up with a possible crash.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    This makes sense and is a good way of explaining this. You're doing almost the exact same `jump` you would when you `return` except you're going to a different, known, safe program counter. – rpecka Apr 18 '19 at 20:36
6

The documentation on error handling in Swift says the following:

... the performance characteristics of a throw statement are comparable to those of a return statement.

So, because you're going to exit the current scope anyway, throwing has hardly any additional cost.

rpecka
  • 1,168
  • 5
  • 17