 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Panic! Macro in Rust Programming
Handling critical errors in Rust is done with the help of panic! Macro. There are other ways to handle errors in Rust, but panic is unique in the sense that it is used to deal with unrecoverable errors.
When we execute the panic! Macro, the whole program unwinds from the stack, and hence, it quits. Because of this manner with which the program quits, we commonly use panic! for unrecoverable errors.
Syntax
The syntax of calling a panic looks like this −
panic!("An error was encountered"); We usually pass a custom message inside the parentheses.
Example
Consider the code shown below as a reference −
fn drink(beverage: &str) {    if beverage == "lemonade" { panic!("AAAaaaaa!!!!"); }    println!("Some refreshing {} is all I need.", beverage); } fn main() {    drink("soda");    drink("lemonade"); } Output
thread 'main' panicked at 'AAAaaaaa!!!!', src/main.rs:3:33 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace Some refreshing soda is all I need.
Note that we are creating panic when we see that the beverage is a “lemonade”. Another more useful case scenario of panic can be something like this −
Example
fn main() {    let x = 3;    let y = 0;    if y == 0 {       panic!("Cannot divide by zero!");    }    println!("{}", x/y); } Output
thread 'main' panicked at 'Cannot divide by zero!', src/main.rs:6:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
Advertisements
 