CodeBlanks Logo Icon CodeBlanks

panic!

Learn unrecoverable errors with panic!.

panic!

panic! reports that the program has entered an unrecoverable state: the message is printed, the stack is unwound and the thread ends. Some operations panic on their own:

let v = vec![1, 2, 3];
// v[10];                 // index out of bounds
// let x: u8 = 255; x + 1; // overflow in a debug build
panic!("yapılandırma bozuk: {}", "port eksik");

RUST_BACKTRACE=1 cargo run shows the call chain at the moment of the panic.

unwind and abort

By default a panic unwinds the stack and runs each value's drop. For a smaller binary, terminating directly can be chosen:

# Cargo.toml
[profile.release]
panic = "abort"

unreachable!(), todo!() and assert!(kosul) are also macros that panic depending on a condition; assert_eq!(a, b) is common in tests.

Practice Precondition

Write fn ikiye_katla(n: i32) -> i32: if n < 0, panic!("negatif değer: {}", n), otherwise return n * 2. Print the result of ikiye_katla(5).

Starter code

main.rs
fn main() {
    // buraya yaz
}

Sample solution

main.rs
fn ikiye_katla(n: i32) -> i32 {
    if n < 0 {
        panic!("negatif değer: {}", n);
    }
    n * 2
}

fn main() {
    println!("{}", ikiye_katla(5));
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is a suitable case for a panic?

  • The user entering a wrong password
  • The network connection dropping
  • A file not being found
  • A logically impossible situation actually happening Correct answer

Explanation: Expected errors caused by the user or the environment should be handled with Result; panic is for bugs.

2 Conditional panic

Question
____(n >= 0, "n negatif olamaz: {}", n);
Answer
assert!(n >= 0, "n negatif olamaz: {}", n);

Explanation: assert! panics with the given message when the condition is false.

3 Macro and where to use it

Term Meaning
panic!(..) Unrecoverable error
assert!(..) Condition check
todo!() Not written yet
unreachable!() An arm that should never run

All lessons in Beginner