← Back to Rust Course | Chapter 10: Error Handling | Lesson 6 of 6

Panic के Basics

एक panic Rust का तुरंत सब कुछ रोकने का तरीका है क्योंकि कुछ seriously, unrecoverably गलत हो गया।
Syntax
rust
panic!("message");

let value = result.unwrap();  // panics on Err or None

Triggering a Panic Explicitly

panic! macro दिए गए message के साथ तुरंत normal program execution रोक देता है, उन situations के लिए उपयोग होता है जो सच में कभी नहीं होनी चाहिए।

उदाहरण: Triggering a Panic Explicitly

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `should_continue`, set to `true`
    let should_continue = true;
    // Check whether `!should_continue`
    if !should_continue {
        panic!("This should never happen");
    }
    // Print "Program continued normally" to the console (with a trailing newline)
    println!("Program continued normally");
}

Panics from Built-in Operations

कई standard operations invalid input पर अपने आप panic करते हैं, जैसे किसी array को bounds से बाहर index करना। यह उदाहरण ऐसा होने से पहले एक safe check दिखाता है।

उदाहरण: Panics from Built-in Operations

markup
// Entry point: execution of the program starts here
fn main() {
    // Declare an immutable variable `numbers`, set to `[1, 2, 3]`
    let numbers = [1, 2, 3];
    // Declare an immutable variable `index`, set to `2`
    let index = 2;
    // Check whether `index < numbers.len()`
    if index < numbers.len() {
        // Print "Safe access: {}" to the console, substituting in `numbers[index]` (with a trailing newline)
        println!("Safe access: {}", numbers[index]);
    // Otherwise, run this branch
    } else {
        // Print "Index out of bounds, avoided panic" to the console (with a trailing newline)
        println!("Index out of bounds, avoided panic");
    }
}

Panic vs Result

panic! programming bugs और सच में unrecoverable states के लिए उपयुक्त है, जबकि Result expected, recoverable failure conditions के लिए उपयुक्त है जिन्हें callers handle करने में सक्षम होने चाहिए।

उदाहरण: Panic vs Result

markup
// Define the function `safe_divide` taking `a`, `b` and returning a `Result<i32, &'static str>`
fn safe_divide(a: i32, b: i32) -> Result<i32, &'static str> {
    // Check whether `b == 0`
    if b == 0 {
        Err("division by zero is an expected, recoverable error")
    // Otherwise, run this branch
    } else {
        Ok(a / b)
    }
}

// Entry point: execution of the program starts here
fn main() {
    // Match on `safe_divide(10, 0)` and branch by pattern
    match safe_divide(10, 0) {
        Ok(v) => println!("{}", v),
        Err(e) => println!("Handled gracefully: {}", e),
    }
}

Catching Panics with catch_unwind

दुर्लभ cases में, std::panic::catch_unwind एक panic catch कर सकता है और इसे पूरे program को crash करने से रोक सकता है, हालांकि यह असामान्य है और proper Result-based error handling का विकल्प नहीं है।

उदाहरण: Catching Panics with catch_unwind

markup
// Bring `std::panic` into scope
use std::panic;

// Entry point: execution of the program starts here
fn main() {
    let result = panic::catch_unwind(|| {
        // Print "About to panic inside catch_unwind" to the console (with a trailing newline)
        println!("About to panic inside catch_unwind");
        panic!("controlled panic");
    });
    // Match on `result` and branch by pattern
    match result {
        Ok(_) => println!("No panic occurred"),
        Err(_) => println!("Panic was caught and handled"),
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. साधारण, expected error conditions के लिए panic! उपयोग करना बजाय एक Result return करने के जिसे callers gracefully handle कर सकें।
  2. यह मान लेना कि एक panic को हमेशा एक exception की तरह catch और recover किया जा सकता है -- default रूप से यह current thread के काम को unwind और terminate करता है।
  3. यह न समझना कि out of bounds indexing, integer overflow (debug builds में), और None/Err पर .unwrap() सभी अपने आप एक panic trigger करते हैं।
चैप्टर सारांश
  • panic!("message") तुरंत normal execution रोकता है और program unwind (या abort) करना शुरू करता है।
  • Out-of-bounds indexing या None पर .unwrap() जैसे आम built-in operations अपने आप एक panic trigger करते हैं।
  • Panics unrecoverable bugs के लिए हैं, expected, everyday error conditions के लिए नहीं -- उनके लिए Result उपयोग करें।
  • RUST_BACKTRACE=1 किसी program को चलाते समय सेट किया जा सकता है ताकि panic होने पर एक पूरा backtrace print हो।
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.