Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

错误处理

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)和不可恢复错误(unrecoverable)。对于 可恢复错误,例如 文件未找到 错误,我们很可能只想向用户报告问题并重试该操作。不可恢复错误 通常是 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.

大多数语言不区分这两类错误,并使用异常(exception)等机制以相同的方式处理它们。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.