Panic! Macro in Rust Programming

Rust ProgrammingServer Side ProgrammingProgramming

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 −

 Live Demo

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
raja
Published on 03-Apr-2021 13:10:30
Advertisements