|
|
|
|
|
by Fellshard
2032 days ago
|
|
I believe the difference is that you resolve the error at the same point where you resolve a successful result, making it impossible for a reader of the function to, for example, assume that you can access a value after an exception was thrown. MyType x = null;
try {
x = doRiskyThing();
x.doThing();
} catch(CheckedException e) { ... }
x.doThing();
This code makes it unclear where the exception is sourced from, and makes it seem like you can use `x` even in a failure scenario. In Rust, however: match doRiskyThing() {
Ok(x) => x.doThing(),
Err(e) => ...
}
Here, it's clear where `x` is available and valid. You could even have the error path panic and merely return `x` if you wanted to use it later on in the method (borrow rules permitted, etc.)A model that fits this more closely in Java is 'try-with-resources'. |
|
In other words, you can be a jackass using either of them, but you can also use them correctly, and when you use them correctly I don't see how they're any different. I also don't feel like the likelihood of using a Result correctly (edit: originally this said _incorrectly_) is substantially higher than a try/catch, but it probably boils down to developer experience and comfort with a particular varietal and not the capabilities inherent in either. Probably. And if not, I'm looking forward to being shown why! :)