# Deinit and throwing initializers

**URL:** <https://forums.swift.org/t/deinit-and-throwing-initializers/38871>\
**Category:** Using Swift\
**Created:** [July 29, 2020, 7:52pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871 "2020-07-29T19:52:32Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![kmahar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmahar/32/5380_2.png) [@kmahar](https://forums.swift.org/u/kmahar)\
**Post date:** [July 29, 2020, 7:52pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/1 "2020-07-29T19:52:32Z")

</div>

Is there a deterministic way to know whether `deinit` will be called for an instance of a class with a throwing initializer when the `init` does throw?

My understanding was that, so long as a type was fully initialized, `deinit` would always be called. However, consider the following code:

```swift
struct Err: Error {
    let message: String
}

class MyClass {
    let x: Int

    init() throws {
        if 1 == 2 {
            throw Err(message: "beforeError")
        }
        self.x = 1

        throw Err(message: "afterErr")
    }

    deinit {
        print("in deinit")
    }
}

do {
    let c = try MyClass()
} catch {
    print("error: \(error)")
}

```

In this case (at least in Swift 5.2.4 on macOS), even though the type is fully initialized before the error is thrown, `deinit` is not called, and the output is:

```swift
error: Err(message: "afterErr")

```

So it seems my prior understanding was incorrect.

If you comment out the first error in the `1 == 2` block, the output becomes:

```swift
in deinit
error: Err(message: "afterErr")

```

This makes it seem like if there is any _possibility_ of throwing before full initialization, `deinit` will not be called. Is that the case?

---

<div class="post-metadata">

**Author:** ![Genaro-Chris](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/genaro-chris/32/24997_2.png) [@Genaro-Chris](https://forums.swift.org/u/Genaro-Chris)\
**Post date:** [July 30, 2020, 2:04pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/2 "2020-07-30T14:04:10Z")

</div>

No, it doesn't call the deinitializer because the error thrown causes the program to cease execution

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 30, 2020, 2:14pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/3 "2020-07-30T14:14:57Z")

</div>

> **Misunderstood the question!**
>
> Based on experimentation, it looks like `deinit` will not be called until the [first phase](https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID220) of the initialization process completes, that is, until all stored properties have been initialized and any `super` initializers have been called.
> 
> If you think about it this is necessary to ensure that you actually have a valid object in `deinit`. If `deinit` were called when you threw `"beforeErr"`, doing something like printing `self.x` in the `deinit` would be an unsafe operation.

---

<div class="post-metadata">

**Author:** ![kmahar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmahar/32/5380_2.png) [@kmahar](https://forums.swift.org/u/kmahar)\
**Post date:** [July 30, 2020, 2:25pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/4 "2020-07-30T14:25:15Z")

</div>

> [@Genaro-Chris](#):
>
> No, it doesn't call the deinitializer because the error thrown causes the program to cease execution

The throwing code is wrapped in a do/catch, so execution is not stopping based on the error. Also, even if it were stopping execution, why would `deinit` only be called in the second case (when there is no possibility of the "before error" being thrown) but not the first? The error comes from exactly the same place in both examples above, the only difference is whether the line where an earlier error may occur is commented out.

> [@Jumhyn](#):
>
> Based on experimentation, it looks like `deinit` will not be called until the [first phase](https://docs.swift.org/swift-book/LanguageGuide/Initialization.html#ID220) of the initialization process completes, that is, until all stored properties have been initialized and any `super` initializers have been called.

That was my understanding too, but I think it's not right; wouldn't you agree that the first phase is already complete when the "afterErr" is thrown, since I've set `self.x`?

My question here is really, why does the presence of a conditional at the start of the `init` method (a conditional which is never actually being executed and is not the source of the thrown error) affect whether `deinit` is called when we throw after the first phase completes?  
That conditional being:

```swift
        if 1 == 2 {
            throw Err(message: "beforeError")
        }

```

---

<div class="post-metadata">

**Author:** ![Jumhyn](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jumhyn/32/3891_2.png) [@Jumhyn](https://forums.swift.org/u/Jumhyn)\
**Post date:** [July 30, 2020, 2:27pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/5 "2020-07-30T14:27:22Z")

</div>

Ah! I missed the point that the conditional was always false 🤦‍♂️. That is interesting behavior that I don't have an explanation for off the top of my head...

---

<div class="post-metadata">

**Author:** ![Dante-Broggi](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dante-broggi/32/7955_2.png) [@Dante-Broggi](https://forums.swift.org/u/Dante-Broggi)\
**Post date:** [July 30, 2020, 3:53pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/6 "2020-07-30T15:53:06Z")

</div>

Before this thread, I would have expected throwing in an init to never run the current class’s deinit, because initialization hasn’t completed yet, but now I have no idea.

I would have also expected that throwing after calling super to run super’s deinit, however, as it has been initialized.

---

<div class="post-metadata">

**Author:** ![kmahar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmahar/32/5380_2.png) [@kmahar](https://forums.swift.org/u/kmahar)\
**Post date:** [August 5, 2020, 9:51pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/9 "2020-08-05T21:51:42Z")

</div>

All very strange. I guess for now the safest approach is to probably have a separate cleanup method and ensure that is called any time an error is being thrown from `init`, since the behavior here doesn't seem particularly reliable.

---

<div class="post-metadata">

**Author:** ![Karl](https://avatars.discourse-cdn.com/v4/letter/k/34f0e0/32.png) [@Karl](https://forums.swift.org/u/Karl)\
**Post date:** [August 5, 2020, 10:49pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/10 "2020-08-05T22:49:49Z")

</div>

I think this warrants a bug report - at the very least, whatever is supposed to happen should be clearly documented somewhere.

---

<div class="post-metadata">

**Author:** ![kmahar](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/kmahar/32/5380_2.png) [@kmahar](https://forums.swift.org/u/kmahar)\
**Post date:** [August 6, 2020, 3:04pm UTC](https://forums.swift.org/t/deinit-and-throwing-initializers/38871/11 "2020-08-06T15:04:48Z")

</div>

I've filed [SR-13355](https://bugs.swift.org/browse/SR-13355).
