Files
book/src/ch09-00-error-handling.md
Chris Krycho 38b2b8537f infra: dprint, part 2
- Reformat everything now that the bug in dprint for wrapping lines with
  inline code is fixed.
- Additionally, apply the formatting rules I *should have* applied the
  first time, so the repo has the same style it has historically used.
2024-12-05 14:05:53 -07:00

1.4 KiB
Raw Permalink Blame History

Error Handling

Errors are a fact of life in software, so Rust has a number of features for handling situations in which something goes wrong. In many cases, Rust requires you to acknowledge the possibility of an error and take some action before your code will compile. This requirement makes your program more robust by ensuring that youll discover errors and handle them appropriately before youve deployed your code to production!

Rust groups errors into two major categories: recoverable and unrecoverable errors. For a recoverable error, such as a file not found error, we most likely just want to report the problem to the user and retry the operation. Unrecoverable errors are always symptoms of bugs, such as trying to access a location beyond the end of an array, and so we want to immediately stop the program.

Most languages dont distinguish between these two kinds of errors and handle both in the same way, using mechanisms such as exceptions. Rust doesnt have exceptions. Instead, it has the type Result<T, E> for recoverable errors and the panic! macro that stops execution when the program encounters an unrecoverable error. This chapter covers calling panic! first and then talks about returning Result<T, E> values. Additionally, well explore considerations when deciding whether to try to recover from an error or to stop execution.