Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Panic and Unwinding | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 20 of 50

·rust

Panic and Unwinding

12 minutes

Course progress40%

Panic and Unwinding

A panic is an unrecoverable error that terminates the program (or thread). Rust provides the panic! macro and strategies for handling panics.

The Panic Macro

fn main() {
    panic!(\"Something went very wrong!\");
    // This line never executes
}

Output:

thread 'main' panicked at 'Something went very wrong!', src/main.rs:2:5

Panic From Unwrapping

Common ways panics occur:

fn main() {
    let x: Option<i32> = None;
    let val = x.unwrap();  // panics: called `Option::unwrap()` on a `None` value
    
    let v = vec![1, 2, 3];
    let item = v[10];  // panics: index out of bounds
    
    let nums = \"abc\";
    let result: i32 = nums.parse().unwrap();  // panics: invalid digit
}

When to Panic

Good Uses

  • Unrecoverable errors: No sensible recovery available
  • Development: Assert assumptions in tests
  • Examples/Prototypes: Simplify code for clarity

Bad Uses

  • Expected failures: Should use Result instead
  • File not found: Use Result and handle gracefully
  • Invalid input: Validate and return error

Assertions

Assert conditions hold, panic if they don't:

fn divide(a: i32, b: i32) -> i32 {
    assert!(b != 0, \"Division by zero!\");
    a / b
}

fn main() {
    // In debug builds, checks are run
    // In release builds, checks are removed (unsafe!)
    let result = divide(10, 2);
    println!(\"Result: {}\", result);
}

Debug vs Release Panics

Debug Mode

let v = vec![1, 2, 3];
let item = v[99];  // panics

Release Mode

Out-of-bounds access is undefined behavior (Rust still checks in safe code though).

Catching Panics

You can catch panics using catch_unwind:**

use std::panic;

fn main() {
    let result = panic::catch_unwind(|| {
        panic!(\"Oops!\")
    });
    
    match result {
        Ok(_) => println!(\"No panic\"),
        Err(_) => println!(\"Caught a panic!\"),
    }
}

Panic Hooks

Customize panics with hooks:

use std::panic;

fn main() {
    panic::set_hook(Box::new(|info| {
        if let Some(s) = info.payload().downcast_ref::<&str>() {
            eprintln!(\"Custom panic handler: {}\", s);
        }
    }));
    
    panic!(\"Something failed\");
}

Unwinding vs Aborting

Two strategies for handling panics:

# In Cargo.toml
[profile.dev]
panic = \"unwind\"    # Default: unwind stack

[profile.release]
panic = \"abort\"     # Faster: immediately exit

Unwind (default):

  • Cleans up resources via drop
  • Slower compilation
  • Allows catching panics

Abort:

  • Immediately terminates
  • Faster code
  • No cleanup

Best Practices

  1. Use Result for possible failures: Not panics
  2. Assert preconditions: In development
  3. Document panic conditions: In documentation
  4. Test panic scenarios: Ensure behavior is expected
  5. Avoid unwrap in libraries: Use Result propagation

Practical Example

fn process_number(s: &str) -> Result<i32, String> {
    // Use Result for recoverable errors
    s.parse::<i32>()
        .map_err(|_| String::from(\"Not a valid number\"))
}

fn main() {
    // Handle Result properly
    match process_number(\"42\") {
        Ok(n) => println!(\"Got: {}\", n),
        Err(e) => println!(\"Error: {}\", e),
    }
    
    // Only use unwrap in examples
    let num = process_number(\"99\").unwrap();  // OK for examples
}
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonError Handling with ResultContinue to lesson 21TraitsBack to Rust Fundamentals curriculum