- Rust 错误处理概述
- panic!
- 为应对 panic,默认是展开或手动中止(abort)调用栈
- https://doc.rust-lang.org/cargo/reference/manifest.html">See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Rust 错误处理概述
- Rust 的可靠性:错误处理
- 大部分情况下:在编译时提示错误,并处理
- 错误分类:
- 可恢复
- 例如文件未找到,可再次尝试
- 不可恢复
- bug,例如访问的索引超出返回
- 可恢复
Rust 没有类似异常的机制
当 panic! 宏执行:
默认情况下,当 panic 发生:
- 程序展开调用栈(工作量大)
- Rust 沿着调用栈往回走
- 清理每个遇到的函数中的数据
- 或立即中止调用栈:
- 不进行清理,直接停止程序
- 内存需要 OS 进行清理
- 程序展开调用栈(工作量大)
- 想让二进制文件更小,把设置从“展开”改为“中止”:
- 在 Cargo.toml 中适当的 profile 部分设置:
- panic=’abort’ ``` [package] name = “demo” version = “0.1.0” authors = [“custer-go custertian@163.com“] edition = “2018”
- 在 Cargo.toml 中适当的 profile 部分设置:
See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
[profile.release] panic = ‘abort’
<a name="Q16Ox"></a>
### 使用 panic! 产生的回溯信息
- panic! 可能出现在:
- 我们写的代码中
- 我们所依赖的代码中
- 可通过调用 panic! 的函数的回溯信息来定位引起问题的代码
```rust
fn main() {
panic!("Crash and burn");
}
运行查看报错信息
thread 'main' panicked at 'Crash and burn', src/main.rs:2:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
fn main() {
let v = vec![1, 2, 3];
v[99];
}
报错信息
thread 'main' panicked at 'index out of bounds:
the len is 3 but the index is 99', src/main.rs:4:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
- 通过设置环境变量 RUST_BACKTRACE 可得到回溯信息
linux 运行 export RUST_BACKTRACE=1 && cargo run
windows 运行 set RUST_BACKTRACE=1 && cargo run
> export RUST_BACKTRACE=1 && cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/string`
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 99', src/main.rs:4:5
stack backtrace:
0: rust_begin_unwind
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/std/src/panicking.rs:493:5
1: core::panicking::panic_fmt
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/panicking.rs:92:14
2: core::panicking::panic_bounds_check
at /rustc/cb75ad5db02783e8b0222fee363c5f63f7e2cf5b/library/core/src/panicking.rs:69:5
3: <usize as core::slice::index::SliceIndex<[T]>>::index
at /Users/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/slice/index.rs:182:10
4: core::slice::index::<impl core::ops::index::Index<I> for [T]>::index
at /Users/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/slice/index.rs:15:9
5: <alloc::vec::Vec<T,A> as core::ops::index::Index<I>>::index
at /Users/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/alloc/src/vec.rs:2161:9
6: string::main
at ./src/main.rs:4:5
7: core::ops::function::FnOnce::call_once
at /Users/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/ops/function.rs:227:5
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
- 为了获取带有调式信息的回溯,必须启用调式符号(不带 —release)