Industrial Training




Rust Unrecoverable Errors with panic!

Unrecoverable Error is an error which is detected, and the programmer can not handle it. When such kind of error occurs, then panic! macro is executed. The panic! prints the failure message. The panic! macro unwinds cleans up the stack and then quit.



    Unwinding: Unwinding is a process of cleaning up the data from the stack memory of each function that it encounters. However, the process of unwinding requires a lot of work. The alternative of Unwinding is an Aborting.
    Aborting: Aborting is a process of ending the program without cleaning the data from the stack memory. The operating system will remove the data. If we switch from unwinding to aborting, then we need to add the following statement:

panic = 'abort';  

Let's see a simple example of panic! macro:


fn main()  
  
   panic!(?No such file exist?);  

Output:

In the above output, the first line shows the error message which conveys two information, i.e., the panic message and the location of the error. The panic message is "no such file exist" and error.rs:3:5 indicates that it is a third line and fifth character of our file error.rs:3:5 file.


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.


Let's see a simple example:
 fn main()  
{  
   let v = vec![20,30,40];  
   print!("element of a vector is :",v[5]);  
}  

Output:

In the above example, we are trying to access the sixth element which is at the index 5. In such a situation, Rust will panic as we are accessing the invalid index. Therefore, Rust will not return anything.
But, in the case of other languages such as C and C++, they would return something, eventhough the vector does not belong to that memory. This is known as Buffer overread, and it leads to the security issues.


Rust Backtrace


Rust Backtrace is the list of all the functions that have been called to know "what happened to cause the errror." We need to set the RUST_BACKTRACE environment variable to get the backtrace.




Hi I am Pluto.