Unrecoverable Error
Rust Unrecoverable Errors with panic!
An error that is identified but that the programmer is unable to fix is known as an unrecoverable error. The panic! macro is run when this kind of problem happens. The panic! message of failure is printed. The panic! macro clears the stack, unwinds, and exits.
Unwinding: Cleaning up the data from each function’s stack memory that it comes across is known as unwinding. That being said, unwinding takes a lot of labor. Aborting is an alternative to Unwinding.
Aborting: The act of terminating a program without removing any data from the stack memory is known as aborting. The data will be deleted by the operating system. In the event that we decide to abort rather than unwind, the following must be added
panic = 'abort';
Example
fn main()
panic!(?No such file exist?);
Output:
The error message in the first line of the output above provides two pieces of information: the fault’s location and a panic message. The error message “no such file exist” is the panic.rs:3:5 denotes that the error in our file is on the third line, fifth character.file with rs:3:5.
Note: Generally, we don’t implement the panic! in our program. Our program code calls the panic! defined in the standard library. The error message that contains the file name and line number is available in someone other?s code where the panic! macro is called.
The Advantage of panic! macro
Rust language does not have a buffer overread issue. Buffer overread is a situation, when reading the data from the buffer and the program overruns the buffer, i.e., it reads the adjacent memory. This leads to the violation of the memory safety.
Example
fn main()
{
let v = vec![20,30,40];
print!("element of a vector is :",v[5]);
}
Output:
We are attempting to access the sixth element, which is located at index 5, in the example above. Rust will become alarmed in this scenario since we are attempting to access an invalid index. Rust won’t return anything as a result.
Other languages, like C and C++, on the other hand, would return something even when the vector was not part of that memory. This is referred to as buffer overread, and it causes security problems.
Rust Backtrace
The Rust Backtrace is an exhaustive list of functions that have been called in order to determine “what happened to cause the errror.” To obtain the backtrace, we must set the RUST_BACKTRACE environment variable.