Open In App

Rust – Unrecoverable Errors

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:



The below program is for unrecoverable error in 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 :

 

 

The below program is for unrecoverable error in Rust.

 




// Rust program for unrecoverable error
 
fn main() {
   let gfg=["cp","algo","ds","FAANG"];
   
   // index 5 does not exist
   // than it will trigger 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

 

Article Tags :