Panic के Basics
In this page:
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
// 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");
}
Login to try C/C++/Java/PHP code in the editor
Panics from Built-in Operations
कई standard operations invalid input पर अपने आप panic करते हैं, जैसे किसी array को bounds से बाहर index करना। यह उदाहरण ऐसा होने से पहले एक safe check दिखाता है।
उदाहरण: Panics from Built-in Operations
// 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");
}
}
Login to try C/C++/Java/PHP code in the editor
Panic vs Result
panic! programming bugs और सच में unrecoverable states के लिए उपयुक्त है, जबकि Result expected, recoverable failure conditions के लिए उपयुक्त है जिन्हें callers handle करने में सक्षम होने चाहिए।
उदाहरण: Panic vs Result
// 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),
}
}
Login to try C/C++/Java/PHP code in the editor
Catching Panics with catch_unwind
दुर्लभ cases में, std::panic::catch_unwind एक panic catch कर सकता है और इसे पूरे program को crash करने से रोक सकता है, हालांकि यह असामान्य है और proper Result-based error handling का विकल्प नहीं है।
उदाहरण: Catching Panics with catch_unwind
// 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"),
}
}
Login to try C/C++/Java/PHP code in the editor
- साधारण, expected error conditions के लिए
panic!उपयोग करना बजाय एकResultreturn करने के जिसे callers gracefully handle कर सकें। - यह मान लेना कि एक panic को हमेशा एक exception की तरह catch और recover किया जा सकता है -- default रूप से यह current thread के काम को unwind और terminate करता है।
- यह न समझना कि 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: