[profile.release] panic = "abort" # abort directly without unwinding
1 2 3 4
fnmain() { println!("Hello world!"); panic!("Oh No! It will crash"); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14
Hello world!
thread 'main' panicked at src/bin/exceptions.rs:3:5: Oh No! It will crash stack backtrace: 0: __rustc::rust_begin_unwind at /rustc/29483883eed69d5fb4db01964cdf2af4d86e9cb2/library/std/src/panicking.rs:697:5 1: core::panicking::panic_fmt at /rustc/29483883eed69d5fb4db01964cdf2af4d86e9cb2/library/core/src/panicking.rs:75:14 2: exceptions::main at ./src/bin/exceptions.rs:3:5 3: core::ops::function::FnOnce::call_once at /home/xiyuanyang/.rustup/toolchains/stable-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ops/function.rs:250:5 note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.
除了显示调用 panic! 之外,代码本身出现严重的漏洞也会引发程序的 panic。
1 2 3 4 5 6 7 8 9
fnmain() { println!("Hello world!"); // panic!("Oh No! It will crash");
letv = vec![1, 23, 4, 5, 5]; // this will cause error, but not a compile error // index out of bounds: the len is 5 but the index is 100 println!("{}", v[100]); }
这是一个经典的数组越界的问题,在 C++ 中会导致 Segmentation Fault(非法的内存访问),在 Rust 中会直接报错 index out of bounds。(当然因为我们使用了封装好的容器)
// definition of Result enums pubenumResult<T, E> { /// Contains the success value #[lang = "Ok"] #[stable(feature = "rust1", since = "1.0.0")] Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
/// Contains the error value #[lang = "Err"] #[stable(feature = "rust1", since = "1.0.0")] Err(#[stable(feature = "rust1", since = "1.0.0")] E), }
fnread_username_from_file() ->Result<String, io::Error> { // this function will read the name (content) from the given file, then return a result type letusername_file_result = File::open("README.md");