book icon indicating copy to clipboard operation
book copied to clipboard

The section on error-handling states panics are unrecoverable, but std::panic states that panics can be caught.

Open lucas75 opened this issue 3 years ago • 1 comments
trafficstars

  • [X] I have checked the latest main branch to see if this has already been fixed
  • [X] I have searched existing issues and pull requests for duplicates

URL to the section(s) of the book with this problem:

  • https://doc.rust-lang.org/nightly/book/ch09-00-error-handling.html
  • https://doc.rust-lang.org/nightly/book/ch09-01-unrecoverable-errors-with-panic.html
  • https://doc.rust-lang.org/nightly/book/ch09-03-to-panic-or-not-to-panic.html

Description of the problem: The section on error handling states panics are unrecoverable, but std::panic states that panics can be caught.

Some examples:

So how do you decide when you should call panic! and when you should return Result? When code panics, there’s no way to recover. (Rust Book; emphasis mine)

Unrecoverable Errors with panic! Sometimes, bad things happen in your code, and there’s nothing you can do about it. In these cases, Rust has the panic! macro. (Rust Book; emphasis mine)

But there is two ways of catching panics:

It is not appropriated to include those catching mechanisms on the error handling section of the book?

lucas75 avatar Oct 15 '22 13:10 lucas75

I also asked this question before, so I would like to share the zullip thread: Question about unrecoverable error.

shinmao avatar Nov 21 '22 17:11 shinmao

Thanks for flagging this up! The basic answer here is “panics are sometimes recoverable, but not reliably so, and you should not in general treat them as recoverable.” They are not like exceptions in Java/Python/C#/etc. in that regard. As noted in the docs for panic::catch_unwind:

Note that this function might not catch all panics in Rust. A panic in Rust is not always implemented via unwinding, but can be implemented by aborting the process as well. This function only catches unwinding panics, not those that abort the process.

Beyond that, many use cases for Rust cannot catch panics: note that those docs are for things from std. Panics cannot be caught in no_std environments!

Given the focus of the book is not “cover every possible path” but “introduce the book overall”, and the many, many caveats that would be involved in explaining in more detail here, I think the framing and level of detail provided by the book is the right one. Closing this accordingly. Perhaps the issue will prove useful to someone else, too, though!

chriskrycho avatar Apr 08 '24 23:04 chriskrycho