Rust Solves The Issues With Exceptions

submited by
Style Pass
2024-11-30 20:00:05

Despite this, exceptions introduce a special try-catch flow which is separate from normal returns and assignments. It prevents ergonomic function composition . You can’t pass the “result” of a throwing function directly into another function, because the return value is passed only when the first function completes successfully. Thrown exceptions aren’t passed in and propagate out instead. This is a very common error-handling pattern, and I get why people want to automate it. But when you need to pass the error data into the second function, Java makes you write a verbose try-catch block and cook a home-made Result type:

Exceptions make this (and similar) patterns suffer so badly. They’re not “uncommon” enough to justify the pain. And, as we’ll see later, “common” error propagation can still be ergonomic without exceptions! They’re not worth the cost.

Can you guess why I used an intermediate variable instead of calling f(g(x)) and f(gException) in try-catch?try { f(g(x)); // <- If `f` also happens to throw `GException` and does this when `g` didn't... } catch (GException gException) { // <- then this will catch `GException` from `f`... f(gException); // <- and then call `f` the second time! 💣 }

Leave a Comment