Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

The panic!() macro is used to emit an unrecoverable error. When the panic!() macro is called, it triggers an immediate exit of the program. The system may also trigger a panic when a fatal error occurs (e.g.: reading/writing an array past the end).

We may call the panic!() macro ourselves to provoke an immediate exit of our program:


thread '<unnamed>' (41094) panicked at src/lib.rs:6:1:
An unrecoverable error occurred!
stack backtrace:
   0: __rustc::rust_begin_unwind
             at /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/std/src/panicking.rs:679:5
   1: core::panicking::panic_fmt
             at /rustc/58cf8f9c35b355199727627d07ae34a4e2846d67/library/core/src/panicking.rs:80:14
   2: ctx::run_user_code_1::{closure#0}
   3: __rust_try
   4: run_user_code_1
   5: <evcxr::runtime::Runtime>::run_loop
   6: evcxr::runtime::runtime_hook
   7: evcxr_jupyter::main
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

33.1.1Unwrapping

Some types like Option or Result have an unwrap() method that returns the contained value or panics if there is no value.

For instance, the find() method of str returns an Option. If we call unwrap() on it, a panic will be thrown if None is returned:


thread '<unnamed>' (41094) panicked at src/lib.rs:22:20:
called `Option::unwrap()` on a `None` value
stack backtrace:
   0: __rustc::rust_begin_unwind

The expect() method is an equivalent to unwrap() but accepts a custom message:


thread '<unnamed>' (41094) panicked at src/lib.rs:22:20:
Character was not found!

Instead of panicking, we may use the unwrap_or() method to return a default value:

0

Or use the unwrap_or_else() method to call a closure that returns a computed default value:

Couldn't automatically determine type of variable `i`.
Please give it an explicit type.

33.1.2Disabling the unwinding of the stack

By default, when panic!() is called Rust unwinds the stack and cleans up data. This operation takes memory space at compile time, and time at runtime. To disable it, place the following lines into the Cargo.toml file:

[profile.release]
panic = 'abort'