Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is deinit called when init throws an exception?

Tags:

swift

Consider the following example class:

class SocketWrapper {
    let sock: Int32

    init() throws {
        try sock = SocketWrapper.createSocket()
    }

    deinit {
        close(sock)
    }
}

What happens if createSocket() throws and the init() therefore fails? sock would be left uninitialized. Is deinit still called (on an partially uninitialized object) when init() throws?

like image 530
Alexander Theißen Avatar asked Mar 26 '26 07:03

Alexander Theißen


1 Answers

deinit is not called on instances that have not been correctly initialized.

If init fails for some reason, then the class instance never starts existing. Therefore, there is no instance on which deinit could be called.

If deinit could be called on a partially initialized instance, it would break the contract of non-optional properties - in your example the socket property would not get assigned and it would still be accessible in deinit as a non-optional but without a value.

like image 190
Sulthan Avatar answered Mar 28 '26 22:03

Sulthan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!