You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
# 错误处理
> [ch09-00-error-handling.md](https://github.com/rust-lang/book/blob/main/src/ch09-00-error-handling.md)
> <br>
> commit 199ca99926f232ee7f581a917eada4b65ff21754
错误是软件中不可否认的事实,所以 Rust 有一些处理出错情况的特性。在许多情况下, Rust 要求你承认错误的可能性,并在你的代码编译前采取一些行动。这一要求使你的程序更加健壮,因为它可以确保你在将代码部署到生产环境之前就能发现错误并进行适当的处理。
Rust 将错误分为两大类:**可恢复的**( *recoverable*)和 ** 不可恢复的**( *unrecoverable*)错误。对于一个可恢复的错误,比如文件未找到的错误,我们很可能只想向用户报告问题并重试操作。不可恢复的错误总是 bug 出现的征兆,比如试图访问一个超过数组末端的位置,因此我们要立即停止程序。
大多数语言并不区分这两种错误, 并采用类似异常这样方式统一处理他们。Rust 没有异常。相反,它有 `Result<T, E>` 类型,用于处理可恢复的错误,还有 `panic!` 宏,在程序遇到不可恢复的错误时停止执行。本章首先介绍 `panic!` 调用,接着会讲到如何返回 `Result<T, E>` 。此外,我们将探讨在决定是尝试从错误中恢复还是停止执行时的注意事项。