Hacker News new | ask | show | jobs
by akx 2020 days ago
Your example smells like a failure of the type system. If that were TypeScript, for the simplest example, you'd explicitly have to type `x` as `MyType | null`, and were that the case, the `x.doThing();` outside the try block would not type-check.
1 comments

It can be encoded in the type system as well. That's really what Java's checked exceptions are: one of the only places in Java where you can specify an alternative 'return' type. But it isn't quite complete enough to use in Java; little quirks here and there make it difficult to use widely, especially since Java 8 and lambdas arrived.

You can still use Java's type system to get something approximating Rust's approach. One upshot of Result-based error handling is that you can often replicate it in any language by shaving off one or two of the biggest benefits to suit that language's constraints.