What is the panic! macro in Rust?

Rust handles critical errors in code with the panic! macro. When this macro executes, the whole program unwinds, that is, the program clears the stack and then quits. Due to the way a program quits after panicking, panic! is commonly used for unrecoverable errors.

Syntax

A custom error message is passed as a parameter that is displayed in the output:

panic!("A critical error was encountered");

The output provides the name of the file, the line where the panic occurred, and the character number where the panic occurred right after the error message.

fn main() {
let x = 5;
let y = 0;
if y == 0 {
panic!("Cannot divide by zero!");
}
println!("{}", x/y);
}

In the output of the program above, main.rs:6:5 is written after the error message, “Cannot divide by zero!”. This means that the panic attack was executed in the file main.rs, at line 6, on character number 5.

Using the Backtrace

There may be times when panic is caused in the code that is called by our program. For such situations, a backtrace is printed on the console to find the name of the file where the program panicked. A backtrace is read from top to bottom until the name of a file we wrote appears. All lines above that point will be the code that our code called.

Execute the code below and analyze the generated backtrace.

use std::env;
fn main() {
// Activating the Backtrace:
env::set_var("RUST_BACKTRACE", "1");
let v = vec![1, 2, 3];
v[3];
}

We can see our file main.rs at line 18 of the backtrace.

The output of the code above first explains the error (“index out of bounds: the len is 3 but the index is 3”) and then displays the name of the file and the line and character number where the panic occurred, that is, src/libcore/slice/mod.rs:2796:10.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved