# \[Pitch N+1\] Typed Throws

**URL:** <https://forums.swift.org/t/pitch-n-1-typed-throws/67496>\
**Category:** Pitches\
**Created:** [September 25, 2023, 4:25am UTC](https://forums.swift.org/t/pitch-n-1-typed-throws/67496 "2023-09-25T04:25:05Z")\
**Posts on this page:** 1\
**Showing post:** 100

<div class="post-metadata">

**Author:** ![1-877-547-7272](https://avatars.discourse-cdn.com/v4/letter/1/278dde/32.png) [@1-877-547-7272](https://forums.swift.org/u/1-877-547-7272)\
**Post date:** [September 27, 2023, 10:59pm UTC](https://forums.swift.org/t/pitch-n-1-typed-throws/67496/100 "2023-09-27T22:59:37Z")

</div>

Some of the links in the table of contents don't work — if the section has code in its title, then the link's URL has the wrong fragment. For example, the link to the section "Typed `rethrows`" tries to take me to #typed--rethrows-, but the correct fragment is #typed-rethrows.

@Douglas_Gregor can you fix this?

* * *

It seems that this proposal could help with testing functions that call `fatalError`, `precondition`, and similar functions, [which is actively being discussed on these forums](https://forums.swift.org/t/testing-fatalerror-and-friends/67317/18). Consider this function:

```swift
func requiresAPositiveNumber(_ number: Int) {
    precondition(number > 0)
    // the rest of the function goes here
}

```

Currently, there's no good way to test that this function disallows numbers that aren't positive, since calling it with a nonpositive number would crash the test suite. Even if you were to isolate the test to a separate thread, the crashed thread [could still leak resources and leave locks in a bad state](https://forums.swift.org/t/testing-fatalerror-and-friends/67317/42). However, with this proposal, we could do this:

```swift
protocol ValidationStrategy {
    associatedtype Failure: Error
    static func validationFailure() throws(Failure) -> Never
}

enum PreconditionValidationStrategy: ValidationStrategy {
    static func validationFailure() -> Never {
        preconditionFailure()
    }
}

enum ThrowingValidationStrategy: ValidationStrategy {
    static func validationFailure() throws(ValidationError) -> Never {
        throw ValidationError()
    }
}
struct ValidationError: Error {}

func requiresAPositiveNumber<V: ValidationStrategy>(
    _ number: Int,
    validationStrategy: V.Type = PreconditionValidationStrategy.self
) throws(V.Failure) {
    guard number > 0 else {
        V.validationFailure()
    }
    // the rest of the function goes here
}

```

Production code would call `requiresAPositiveNumber` with `PreconditionValidationStrategy` and the function would act the same as the original function (including its non-throwing signature), but test code could call it with `ThrowingValidationStrategy` and verify that the function correctly rejects non-positive numbers.

---

_[View the full topic](https://forums.swift.org/t/pitch-n-1-typed-throws/67496)._
