Skip to content
Related Articles

Related Articles

Rust – Unrecoverable Errors
  • Last Updated : 22 Mar, 2021

Unrecoverable errors are those errors which as the name suggests can not be handled by a programmer. When any unrecoverable error occurs the end result is the program quits (terminates). The complete process is the first panic! macro is fired then the error message is printed along with the location of it and finally, the program is terminated. It mostly arises due to the bugs left by the programmer in the code.

Example 1:

  • In this example, we will call panic! macro.
  • It will show our error message and the complete stack trace(location, message).
  • After this, it unwinds and cleans up the stack, and then quit(terminate the program).

The below program is for unrecoverable error in Rust.

Rust




// Rust program for unrecoverable error
  
fn main() {
    
   // this will result in unrecoverable error
   panic!("gfg called panic macro");
}

Output :



thread 'main' panicked at 'gfg called panic macro', src\main.rs:4:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
error: process didn't exit successfully: `target\debug\unrecoverableErrors.exe` (exit code: 101)

Example 2 :

  • In this program, we will define one gfg array which will consist of four strings.
  • Now we will try to print 5 element in the array and because the length is 4 [0-3] and we are looking for 5th index than it will trigger panic! macro.
  • After this, it will print the error message, location, and stack trace.

The below program is for unrecoverable error in Rust.

Rust




// Rust program for unrecoverable error
  
fn main() {
   let gfg=["cp","algo","ds","FAANG"]; 
    
   // index 5 does not exist 
   // than it will triger panic! macro
   println!("{}", gfg[5]);
}

Output :

error: this operation will panic at runtime
 --> src\main.rs:5:20
  |
5 |     println!("{}", gfg[5]);
  |                    ^^^^^^ index out of bounds: the length is 4 but the index is 5
  |
  = note: `#[deny(unconditional_panic)]` on by default
My Personal Notes arrow_drop_up
Recommended Articles
Page :