Hacker News new | ask | show | jobs
by forrestthewoods 668 days ago
Rust panics are basically exceptions, aren’t they? Typically they aren’t caught without terminating. But you totally can. And if you’re writing a service that runs in the background you’ll probably have to.
2 comments

Rust Result is basically a checked exception. Java makes you choose between adding an exception to "throws" or catching it, Rust makes you choose between declaring your function as returning Result or checking if you got an Err.

The only difference is that Rust has better syntactic sugar for the latter, but Result is really isomorphic to Java checked exceptions.

Panic could be said to be the same as an unchecked exception, except you have a lot more control on what causes them. The panic you get from calling unwrap() on an Option is the same as a NullPointerException, but you have full control on which points of the program that can generate it.

Rust goes to substantial lengths to allow unwinding from panics. For example, see how complicated `Vec::retain_mut` is. The complexity is due to the possibility of a panic, and the need to unwind.

https://doc.rust-lang.org/1.80.1/src/alloc/vec/mod.rs.html#1...

I’ve never written any Java so your comparisons are lost on me.

Rust Result is great. I love it.

The root article was talking about C++. Rust panic is basically the same as a C++ exception afaict. With the caveat that Rust discourages catching and resuming from panics. But you can!

Catching panics is best-effort only. In general, Rust panics can't be caught. (Even if a program is compiled with panic=unwind, this can change to abort at run-time.)
I don’t think that’s correct. Panics can be configured to abort instead of unwind. But if panic != abort then catching should be reliable.

https://doc.rust-lang.org/std/panic/fn.catch_unwind.html