How can we add an exception during the code check

This is for a recent pull request I made. I have a "try!" in my next, but that code path is never triggered during a throwing predicate, so it won't actually crash.

Are you asking for an alternative to try! throwingNext() to get past the “format check” step?

I see fatalError used within this repo (for presumably more meaningful messages than one might divine from try!). So maybe:

public mutating func next() -> (value: Base.Element, count: Int)? {
    do {
        return try throwingNext()
    } catch {
        fatalError("This method is called only when the predicate does not `throw`, but it threw: \(error)")
    }
}

Or, if as your comment suggests, if it is really impossible to fail:

public mutating func next() -> (value: Base.Element, count: Int)? {
    // NOTE: This method is called only when the predicate does not `throw`,
    // so `try?` is OK.
    try? throwingNext()
}

I would lean towards the former over the latter (so if problems arise, developers have a prayer to diagnose the problem).

Alternatively, if it really cannot fail, the entire presence of throwingNext feels a bit suspect, but I haven’t gone through the whole PR in detail, so I can’t comment on that. The question would seem to be whether this can be refactored to avoid throwingNext pattern, entirely…

1 Like

throwingNext is for the eager version of the function, so I can share code between the eager and lazy versions.

OK. I had to ask. :wink:

Anyway, given that this repo won’t accept try! (a rule enforced by many projects), then the do-try-catch-fatalError is probably the way to go. Good luck.

Some source-code evaluation software support special comments to ignore certain sections. I was wondering if such a thing exists for the pull-request's checker.

With swift-format, the format checker used by the Algorithms library, you can use a comment to disable rules for a line or a file. We only use the line-based disabling in the project – you can see usage of disabling the NeverForceUnwrap rule several times in FlattenCollection.swift.

In my experience these rules are most useful in providing some friction against using less-safe practices, so disabling them when it makes sense, and providing a comment explaining why, is totally fine.

2 Likes