x-i18n: generated_at: “2026-03-01T14:00:31Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: 8c5d97ecf63d50fcb053197176dc31544d19add7df3c60e61791b95659890733 source_path: ch09-00-error-handling.md workflow: 16
错误处理 (Error Handling)
Error Handling
错误在软件开发中是无法避免的事实,因此 Rust 提供了许多功能来处理出现问题的情况。在许多情况下,Rust 要求你承认错误的可能性,并采取一些行动,然后你的代码才能编译。这一要求确保你在将代码部署到生产环境之前,能够发现并适当地处理错误,从而使你的程序更加健壮!
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 you’ll discover errors and handle them appropriately before deploying your code to production!
Rust 将错误分为两大类:可恢复错误和不可恢复错误。对于“可恢复错误 (recoverable error)”,例如“找不到文件”错误,我们很可能只想向用户报告问题并重试操作。“不可恢复错误 (unrecoverable errors)”通常是 bug 的征兆,例如尝试访问数组末尾之外的位置,因此我们希望立即停止程序。
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.
大多数语言不区分这两类错误,并以相同的方式处理它们,使用诸如异常 (exceptions) 之类的机制。Rust 没有异常。相反,它为可恢复错误提供了 Result<T, E> 类型,并提供了 panic! 宏,当程序遇到不可恢复错误时停止执行。本章首先介绍调用 panic!,然后讨论返回 Result<T, E> 值。此外,我们将探讨在决定是尝试从错误中恢复还是停止执行时的考虑因素。
Most languages don’t distinguish between these two kinds of errors and handle
both in the same way, using mechanisms such as exceptions. Rust doesn’t 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, we’ll explore
considerations when deciding whether to try to recover from an error or to stop
execution.