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


x-i18n: generated_at: “2026-03-01T14:04:03Z” model: gemini-3-flash-preview provider: google-gemini-cli source_hash: a3f14104d56462a27c3d2b3a0cdb19eb7aaa4176ad1d80b82b0d6d667304d54e source_path: ch09-03-to-panic-or-not-to-panic.md workflow: 16

panic! 还是不要 panic! (To panic! or Not to panic!)

To panic! or Not to panic!

那么,你如何决定什么时候该调用 panic!,什么时候该返回 Result?当代码恐慌时,就无法恢复了。你可以为任何错误情况调用 panic!,无论是否有恢复的可能,但那样你就是在代表调用代码决定该情况是不可恢复的。当你选择返回一个 Result 值时,你就给了调用代码选择的余地。调用代码可以选择尝试以适合其情况的方式进行恢复,也可以决定在这种情况下 Err 值是不可恢复的,因此它可以调用 panic! 并将你的可恢复错误转变为不可恢复的错误。因此,在定义一个可能会失败的函数时,返回 Result 是一个很好的默认选择。

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. You could call panic! for any error situation, whether there’s a possible way to recover or not, but then you’re making the decision that a situation is unrecoverable on behalf of the calling code. When you choose to return a Result value, you give the calling code options. The calling code could choose to attempt to recover in a way that’s appropriate for its situation, or it could decide that an Err value in this case is unrecoverable, so it can call panic! and turn your recoverable error into an unrecoverable one. Therefore, returning Result is a good default choice when you’re defining a function that might fail.

在示例、原型代码和测试等情况下,编写会恐慌的代码而不是返回 Result 更为合适。让我们探讨一下原因,然后讨论编译器无法判断失败是不可能的,但作为人类的你可以判断的情况。本章将以关于如何在库代码中决定是否引发恐慌的一些通用指南作为结束。

In situations such as examples, prototype code, and tests, it’s more appropriate to write code that panics instead of returning a Result. Let’s explore why, then discuss situations in which the compiler can’t tell that failure is impossible, but you as a human can. The chapter will conclude with some general guidelines on how to decide whether to panic in library code.

示例、原型代码和测试 (Examples, Prototype Code, and Tests)

Examples, Prototype Code, and Tests

当你正在编写一个示例来说明某个概念时,包含健壮的错误处理代码可能会使示例变得不那么清晰。在示例中,人们理解对像 unwrap 这样可能引发恐慌的方法的调用,其意图是作为你希望应用程序处理错误方式的一个占位符,处理方式可以根据你的其余代码正在做的事情而有所不同。

When you’re writing an example to illustrate some concept, also including robust error-handling code can make the example less clear. In examples, it’s understood that a call to a method like unwrap that could panic is meant as a placeholder for the way you’d want your application to handle errors, which can differ based on what the rest of your code is doing.

类似地,当你正在开发原型且尚未准备好决定如何处理错误时,unwrapexpect 方法非常方便。它们在你的代码中留下了清晰的标记,以便在你准备好让程序更健壮时使用。

Similarly, the unwrap and expect methods are very handy when you’re prototyping and you’re not yet ready to decide how to handle errors. They leave clear markers in your code for when you’re ready to make your program more robust.

如果测试中的某个方法调用失败,你会希望整个测试都失败,即使该方法不是被测试的功能。因为 panic! 是测试被标记为失败的方式,所以调用 unwrapexpect 正是应该发生的事情。

If a method call fails in a test, you’d want the whole test to fail, even if that method isn’t the functionality under test. Because panic! is how a test is marked as a failure, calling unwrap or expect is exactly what should happen.

当你拥有比编译器更多信息时 (When You Have More Information Than the Compiler)

When You Have More Information Than the Compiler

当你拥有一些其他逻辑能确保 Result 肯定拥有 Ok 值,但该逻辑不是编译器能理解的东西时,调用 expect 也是合适的。你仍然需要处理一个 Result 值:无论你调用的是什么操作,通常仍有失败的可能性,尽管在你特定的情况下逻辑上是不可能的。如果你可以通过手动检查代码来确保永远不会得到 Err 变体,那么调用 expect 并在参数文本中记录你认为永远不会得到 Err 变体的原因是完全可以接受的。这里有一个例子:

It would also be appropriate to call expect when you have some other logic that ensures that the Result will have an Ok value, but the logic isn’t something the compiler understands. You’ll still have a Result value that you need to handle: Whatever operation you’re calling still has the possibility of failing in general, even though it’s logically impossible in your particular situation. If you can ensure by manually inspecting the code that you’ll never have an Err variant, it’s perfectly acceptable to call expect and document the reason you think you’ll never have an Err variant in the argument text. Here’s an example:

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/no-listing-08-unwrap-that-cant-fail/src/main.rs:here}}
}

我们正在通过解析一个硬编码字符串来创建一个 IpAddr 实例。我们可以看到 127.0.0.1 是一个有效的 IP 地址,因此在这里使用 expect 是可以接受的。然而,拥有一个硬编码的、有效的字符串并不会改变 parse 方法的返回类型:我们仍然得到一个 Result 值,并且编译器仍然会要求我们像 Err 变体可能存在一样处理 Result,因为编译器不够聪明,无法看出这个字符串始终是一个有效的 IP 地址。如果 IP 地址字符串来自用户而不是硬编码在程序中,因此“确实”有失败的可能性,我们肯定会希望以一种更健壮的方式来处理 Result。提到这个 IP 地址是硬编码的假设,将促使我们在将来如果需要从其他来源获取 IP 地址时,将 expect 更改为更好的错误处理代码。

We’re creating an IpAddr instance by parsing a hardcoded string. We can see that 127.0.0.1 is a valid IP address, so it’s acceptable to use expect here. However, having a hardcoded, valid string doesn’t change the return type of the parse method: We still get a Result value, and the compiler will still make us handle the Result as if the Err variant is a possibility because the compiler isn’t smart enough to see that this string is always a valid IP address. If the IP address string came from a user rather than being hardcoded into the program and therefore did have a possibility of failure, we’d definitely want to handle the Result in a more robust way instead. Mentioning the assumption that this IP address is hardcoded will prompt us to change expect to better error-handling code if, in the future, we need to get the IP address from some other source instead.

错误处理指南 (Guidelines for Error Handling)

Guidelines for Error Handling

建议在你的代码可能最终陷入糟糕状态时,让代码引发恐慌。在这种语境下,“糟糕状态 (bad state)”是指某些假设、保证、合同或不变式被破坏的情况,例如当无效值、矛盾值或缺失值被传递给你的代码时——加上以下一种或多种情况:

It’s advisable to have your code panic when it’s possible that your code could end up in a bad state. In this context, a bad state is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to your code—plus one or more of the following:

  • 糟糕状态是某种意料之外的事情,而不是像用户以错误格式输入数据这样可能偶尔发生的事情。

  • 在此之后,你的代码需要依赖于“不”处于这种糟糕状态,而不是在每一步都检查问题。

  • 在你使用的类型中没有好的方式来编码这些信息。我们将在第 18 章的“将状态和行为编码为类型”中演示我们的意思。

  • The bad state is something that is unexpected, as opposed to something that will likely happen occasionally, like a user entering data in the wrong format.

  • Your code after this point needs to rely on not being in this bad state, rather than checking for the problem at every step.

  • There’s not a good way to encode this information in the types you use. We’ll work through an example of what we mean in “Encoding States and Behavior as Types” in Chapter 18.

如果有人调用你的代码并传入了不合理的值,如果可以的话,最好返回一个错误,以便库的使用者可以在那种情况下决定他们想做什么。然而,在继续运行可能不安全或有害的情况下,最好的选择可能是调用 panic! 并提醒使用你的库的人他们的代码中存在 bug,以便他们在开发期间修复它。同样,如果你正在调用不受你控制的外部代码,并且它返回了一个你无法修复的无效状态,那么 panic! 通常是合适的。

If someone calls your code and passes in values that don’t make sense, it’s best to return an error if you can so that the user of the library can decide what they want to do in that case. However, in cases where continuing could be insecure or harmful, the best choice might be to call panic! and alert the person using your library to the bug in their code so that they can fix it during development. Similarly, panic! is often appropriate if you’re calling external code that is out of your control and returns an invalid state that you have no way of fixing.

然而,当失败是预期之中的,返回一个 Result 比调用 panic! 更合适。例子包括解析器被给定了格式错误的数据,或者 HTTP 请求返回了一个指示你已达到速率限制的状态。在这些情况下,返回一个 Result 表明失败是一个预期的可能性,调用代码必须决定如何处理。

However, when failure is expected, it’s more appropriate to return a Result than to make a panic! call. Examples include a parser being given malformed data or an HTTP request returning a status that indicates you have hit a rate limit. In these cases, returning a Result indicates that failure is an expected possibility that the calling code must decide how to handle.

当你的代码执行一个如果使用无效值调用可能会让用户面临风险的操作时,你的代码应该首先验证这些值是否有效,如果无效则引发恐慌。这主要是出于安全原因:尝试操作无效数据可能会使你的代码暴露在漏洞之下。这是标准库在你尝试越界内存访问时会调用 panic! 的主要原因:尝试访问不属于当前数据结构的内存是一个常见的安全问题。函数通常有“合同 (contracts)”:只有在输入满足特定要求时,它们的行为才能得到保证。在违反合同时引发恐慌是有道理的,因为违反合同总是意味着调用方存在 bug,而且这不是你希望调用代码必须显式处理的那种错误。事实上,调用代码没有合理的恢复方式;调用方的“程序员”需要修复代码。函数的合同,特别是违反合同时会引起恐慌的情况,应该在函数的 API 文档中解释。

When your code performs an operation that could put a user at risk if it’s called using invalid values, your code should verify the values are valid first and panic if the values aren’t valid. This is mostly for safety reasons: Attempting to operate on invalid data can expose your code to vulnerabilities. This is the main reason the standard library will call panic! if you attempt an out-of-bounds memory access: Trying to access memory that doesn’t belong to the current data structure is a common security problem. Functions often have contracts: Their behavior is only guaranteed if the inputs meet particular requirements. Panicking when the contract is violated makes sense because a contract violation always indicates a caller-side bug, and it’s not a kind of error you want the calling code to have to explicitly handle. In fact, there’s no reasonable way for calling code to recover; the calling programmers need to fix the code. Contracts for a function, especially when a violation will cause a panic, should be explained in the API documentation for the function.

然而,在所有函数中进行大量的错误检查会很冗长且令人厌烦。幸运的是,你可以使用 Rust 的类型系统(以及编译器进行的类型检查)来为你完成许多检查。如果你的函数有一个特定类型作为参数,你可以继续编写代码逻辑,因为知道编译器已经确保了你拥有一个有效值。例如,如果你有一个类型而不是 Option,那么你的程序期望得到“某个东西”而不是“无”。这样你的代码就不必处理 SomeNone 变体的两种情况:它只会有一种肯定拥有值的情况。尝试向你的函数传递“无”的代码甚至无法通过编译,因此你的函数不必在运行时检查该情况。另一个例子是使用无符号整数类型(如 u32),这确保了参数永远不会是负数。

However, having lots of error checks in all of your functions would be verbose and annoying. Fortunately, you can use Rust’s type system (and thus the type checking done by the compiler) to do many of the checks for you. If your function has a particular type as a parameter, you can proceed with your code’s logic knowing that the compiler has already ensured that you have a valid value. For example, if you have a type rather than an Option, your program expects to have something rather than nothing. Your code then doesn’t have to handle two cases for the Some and None variants: It will only have one case for definitely having a value. Code trying to pass nothing to your function won’t even compile, so your function doesn’t have to check for that case at runtime. Another example is using an unsigned integer type such as u32, which ensures that the parameter is never negative.

用于验证的自定义类型 (Custom Types for Validation)

Custom Types for Validation

让我们更进一步,利用 Rust 类型系统确保我们拥有一个有效值的想法,并看看如何创建一个用于验证的自定义类型。回想一下第 2 章中的猜谜游戏,我们的代码要求用户猜一个 1 到 100 之间的数字。在将其与我们的秘密数字进行核对之前,我们从未验证用户的猜测是否在这些数字之间;我们只验证了猜测是正数。在这种情况下,后果并不是非常严重:我们输出的“太高”或“太低”仍然是正确的。但是,引导用户进行有效的猜测,并在用户猜出一个超出范围的数字与用户键入(例如)字母时产生不同的行为,将是一个有用的增强。

Let’s take the idea of using Rust’s type system to ensure that we have a valid value one step further and look at creating a custom type for validation. Recall the guessing game in Chapter 2 in which our code asked the user to guess a number between 1 and 100. We never validated that the user’s guess was between those numbers before checking it against our secret number; we only validated that the guess was positive. In this case, the consequences were not very dire: Our output of “Too high” or “Too low” would still be correct. But it would be a useful enhancement to guide the user toward valid guesses and have different behavior when the user guesses a number that’s out of range versus when the user types, for example, letters instead.

一种方法是将猜测解析为 i32 而不仅仅是 u32 以允许潜在的负数,然后添加一个检查数字是否在范围内的判断,如下所示:

One way to do this would be to parse the guess as an i32 instead of only a u32 to allow potentially negative numbers, and then add a check for the number being in range, like so:

文件名: src/main.rs

{{#rustdoc_include ../listings/ch09-error-handling/no-listing-09-guess-out-of-range/src/main.rs:here}}

if 表达式检查我们的值是否超出范围,将问题告知用户,并调用 continue 开始循环的下一次迭代并请求另一个猜测。在 if 表达式之后,我们可以继续进行 guess 和秘密数字之间的比较,因为知道 guess 在 1 到 100 之间。

The if expression checks whether our value is out of range, tells the user about the problem, and calls continue to start the next iteration of the loop and ask for another guess. After the if expression, we can proceed with the comparisons between guess and the secret number knowing that guess is between 1 and 100.

然而,这并不是一个理想的解决方案:如果程序只在 1 到 100 之间的值上操作是绝对关键的,并且它有许多具有此要求的函数,那么在每个函数中进行这样的检查将是乏味的(并且可能会影响性能)。

However, this is not an ideal solution: If it were absolutely critical that the program only operated on values between 1 and 100, and it had many functions with this requirement, having a check like this in every function would be tedious (and might impact performance).

相反,我们可以建立一个新类型并在一个专门的模块中将验证放在一个函数中以创建该类型的实例,而不是到处重复验证。这样,函数在签名中使用新类型并放心地使用它们接收到的值就是安全的。示例 9-13 展示了定义 Guess 类型的一种方法,只有当 new 函数接收到 1 到 100 之间的值时,它才会创建一个 Guess 实例。

Instead, we can make a new type in a dedicated module and put the validations in a function to create an instance of the type rather than repeating the validations everywhere. That way, it’s safe for functions to use the new type in their signatures and confidently use the values they receive. Listing 9-13 shows one way to define a Guess type that will only create an instance of Guess if the new function receives a value between 1 and 100.

#![allow(unused)]
fn main() {
{{#rustdoc_include ../listings/ch09-error-handling/listing-09-13/src/guessing_game.rs}}
}

注意 src/guessing_game.rs 中的这段代码依赖于在 src/lib.rs 中添加一个模块声明 mod guessing_game;,我们在这里没有展示。在这个新模块的文件中,我们定义了一个名为 Guess 的结构体,它有一个名为 value 的字段,持有一个 i32。这就是存储数字的地方。

Note that this code in src/guessing_game.rs depends on adding a module declaration mod guessing_game; in src/lib.rs that we haven’t shown here. Within this new module’s file, we define a struct named Guess that has a field named value that holds an i32. This is where the number will be stored.

然后,我们在 Guess 上实现了一个名为 new 的关联函数,用于创建 Guess 值的实例。new 函数被定义为具有一个名为 valuei32 类型的参数,并返回一个 Guessnew 函数体内的代码测试 value 以确保其在 1 到 100 之间。如果 value 未通过此测试,我们发起一个 panic! 调用,这将提醒编写调用代码的程序员他们有一个需要修复的 bug,因为创建一个 value 在此范围之外的 Guess 会违反 Guess::new 所依赖的合同。Guess::new 可能发生恐慌的条件应该在其面向公众的 API 文档中讨论;我们将在第 14 章介绍 API 文档中指示 panic! 可能性的文档惯例。如果 value 确实通过了测试,我们创建一个新的 Guess,其 value 字段设置为 value 参数的值,并返回该 Guess

Then, we implement an associated function named new on Guess that creates instances of Guess values. The new function is defined to have one parameter named value of type i32 and to return a Guess. The code in the body of the new function tests value to make sure it’s between 1 and 100. If value doesn’t pass this test, we make a panic! call, which will alert the programmer who is writing the calling code that they have a bug they need to fix, because creating a Guess with a value outside this range would violate the contract that Guess::new is relying on. The conditions in which Guess::new might panic should be discussed in its public-facing API documentation; we’ll cover documentation conventions indicating the possibility of a panic! in the API documentation that you create in Chapter 14. If value does pass the test, we create a new Guess with its value field set to the value parameter and return the Guess.

接下来,我们实现一个名为 value 的方法,它借用 self,没有其他参数,并返回一个 i32。这种方法有时被称为 getter,因为它的目的是从字段中获取某些数据并返回它。这个公有方法是必要的,因为 Guess 结构体的 value 字段是私有的。value 字段必须是私有的,这一点很重要,这样使用 Guess 结构体的代码就不被允许直接设置 valueguessing_game 模块之外的代码“必须”使用 Guess::new 函数来创建一个 Guess 实例,从而确保没有办法让 Guess 拥有一个未经 Guess::new 函数中条件检查的 value

Next, we implement a method named value that borrows self, doesn’t have any other parameters, and returns an i32. This kind of method is sometimes called a getter because its purpose is to get some data from its fields and return it. This public method is necessary because the value field of the Guess struct is private. It’s important that the value field be private so that code using the Guess struct is not allowed to set value directly: Code outside the guessing_game module must use the Guess::new function to create an instance of Guess, thereby ensuring that there’s no way for a Guess to have a value that hasn’t been checked by the conditions in the Guess::new function.

具有参数或仅返回 1 到 100 之间数字的函数,随后可以在其签名中声明它接收或返回的是一个 Guess 而不是一个 i32,并且在其主体中不需要进行任何额外的检查。

A function that has a parameter or returns only numbers between 1 and 100 could then declare in its signature that it takes or returns a Guess rather than an i32 and wouldn’t need to do any additional checks in its body.

总结 (Summary)

Summary

Rust 的错误处理功能旨在帮助你编写更健壮的代码。panic! 宏发出信号,表明你的程序处于它无法处理的状态,并允许你告诉进程停止运行,而不是尝试继续使用无效或不正确的值。Result 枚举利用 Rust 的类型系统来指示操作可能会以你的代码可以恢复的方式失败。你可以使用 Result 来告诉调用你代码的代码,它也需要处理潜在的成功或失败。在适当的情况下使用 panic!Result 将使你的代码在面对不可避免的问题时更加可靠。

Rust’s error-handling features are designed to help you write more robust code. The panic! macro signals that your program is in a state it can’t handle and lets you tell the process to stop instead of trying to proceed with invalid or incorrect values. The Result enum uses Rust’s type system to indicate that operations might fail in a way that your code could recover from. You can use Result to tell code that calls your code that it needs to handle potential success or failure as well. Using panic! and Result in the appropriate situations will make your code more reliable in the face of inevitable problems.

既然你已经看到了标准库在 OptionResult 枚举中使用泛型的有用方式,我们将讨论泛型是如何工作的,以及你如何在代码中使用它们。

Now that you’ve seen useful ways that the standard library uses generics with the Option and Result enums, we’ll talk about how generics work and how you can use them in your code.