Swift vs Obj-C exception. What is stack unwinding? Why doesn't the strip do this?

There is a note in Swift Docs that states the following:

Error handling in Swift is similar to handling exceptions in other languages ​​using the try, catch, and throw keywords. Unlike exception handling in many languages, including Objective-C -error handling in Swift is not associated with expanding the call stack, a process that can be expensive. Thus, the performance characteristics of the throw expression are comparable to those of the return statement.

What does unlocking the call stack in Swift and Obj-c mean? A related question , but this is C ++. I know what a call stack is, but I would like a more detailed explanation for unwinding.

If Swift does not unwind the call stack, what does it do instead?

Why can it be expensive?

Bottom line: I would like to better understand how exceptions and the workflow in Swift work.

+5
source share
1 answer

Decoupling the stack basically means that when an exception is thrown, the method immediately aborts, the calling method aborts immediately, and so on, until an exception handler ( try-catch-finally ) is found or until we reach the top of the stack, when the exception usually ends by interrupting the current thread .

This works well in languages ​​with a garbage collector, but in general it can lead to a memory leak in languages ​​with manual memory management. In addition, since methods are aborted in unexpected places, an exception often leads to undefined / unrecoverable program states.

This is why an exception in all languages ​​should be used sparingly and only to handle exceptional situations, and not to handle the normal flow of a program.

Obj-C exceptions were not very good, with all the problems mentioned above (see NSException , @ try-@catch- @finally ), so no one uses them. Instead, Obj-C came up with error parameters (you pass a reference to the NSError variable, and if this method fails, the error is assigned to this variable). See Error Handling in Objective-C

Swift just appeared with a different syntax for NSError . This is not real exception handling (errors do not interrupt program execution). See Error Handling in Swift

Technically, every method / method that can cause an error in Swift has an additional hidden parameter that is used to pass the error back to the caller’s context.

If you need more information, simply compare the code in Swift 1.x and 2.x (1.x does not yet have a special grammar for error handling).

+2
source

Source: https://habr.com/ru/post/1246458/


All Articles