Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Anyhow erases the type of the error, but still indicates the possibility of some error and forces you to handle it. Functionality-wise, it's very similar to `throws Exception` in Java. Read my post




As a matter of fact I did when it appeared on hn.

>forces you to handle it.

By writing `?`) And we get poor man's exceptions.


Poor man's checked exceptions. That's important. From the `?` you always see which functions can fail and cause an early return. You can confidently refactor and use local reasoning based on the function signature. The compiler catches your mistakes when you call a fallible function from a supposedly infallible function, and so on. Unchecked exceptions don't give you any of that. Java's checked exceptions get close and you can use `throws Exception` very similarly to `anyhow::Result`. But Java doesn't allow you to be generic over checked exceptions (as discussed in the post). This is a big hurdle that makes Result superior.

>Poor man's checked exceptions.

No, it's not quite the same. Checked exceptions force you to deal with them one way or another. When you use `?` and `anyhow` you just mark a call of fallible function as such (which is a plus, but the it's the only plus), and don't think even for a second about handling it.


Checked exceptions don't force you to catch them on every level. You can mark the caller as `throws Exception` just like you can mark the caller as returning `anyhow::Result`. There is no difference in this regard.

If anything, `?` is better for actual "handling". It's explicit and can be questioned in a code review, while checked exceptions auto-propagate quietly, you don't see where it happens and where a local `catch` would be more appropriate. See the "Can you guess" section of the post. It discusses this.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: