[SE-0413: Typed throws] needs union types

It is hard to use if it allow throw only one type Error.

throws(ErrorTypeA | ErrorTypeB) should be allowed

Most of the cases are throwing multiple type Error.

1 Like

The proposal says:

8 Likes

Yes. Thanks for pointing out. Without Union type (or sum type), the typed error means nothing for most developer using cases.

I’ll repeat the argument from the original proposal discussion against this: if you throw two errors today, how do you know you won’t throw three errors tomorrow? A dedicated enum type (wrapping the two errors in their own cases) can handle this in a source-compatible way*; untyped throws or even a custom protocol can as well, with no claims of exhaustive case matching; but plain old anonymous union types, like tuples, would break callers as soon as you need to add a third possibility.

* …if we get around to adding a frozen/non-frozen distinction for enums in libraries that aren’t using the binary-compatible library evolution mode. Which admittedly is not much less hypothetical than anonymous union types, but is a little more scoped, and anyway the language recommendation is still to prefer untyped errors.

9 Likes

I'm pretty sure this accepted SE feature needs a sum type. We'll see when developer or framework team using this typed error feature without sum type, will make a lot of unnecessary enum error types. Declaring and naming these kind of Enums is ridiculous.

1 Like

It sounds like you should just be throwing Error. You don't have to use typed throws just because it was added to the language.

17 Likes

You can use Either<ErrorA, ErrorB> or similar OneOfThree<A, B, C> enum for ability to throw two / three Error Types. Does it cover your cases?

I kindly disagree. Most developers use enums for errors already today. And for good reason. No union or sum type needed. Predictable, nice, and easy.

To convince people, you would need to show us practical examples where an enum or any Error does not work and where what you ask for would be much better.

5 Likes

If a new error is added to the union, then when updating the library won’t there be a compilation error where the errors are caught? So the library user just has to update their code as expected? Or am I missing a point here?

That’s not “source-compatible”; you’d have to release a new SemVer-major version to make that change and not mess up existing clients. It’d be fine within a single package, though.

4 Likes