Open In App

Rust – Panic Error Handling Mechanism

Last Updated : 29 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, the error-handling mechanism is via the use of the panic keyword. Rust handles error handling by grouping the errors into two categories – Recoverable errors and nonrecoverable errors. The former deals with errors related to file not found while the latter deals with errors related to code compilation, bugs in code, or situations where location is accessed beyond range.

Rust specifically uses the Result<T, E> trait for handling recoverable errors and panic! macro comes into play when unrecoverable errors are encountered. The panic macro keyword handles the nonrecoverable errors. The panic macro takes action by taking appropriate actions by calling the panic! keyword.

Example 1:

Rust




fn main() {
    panic!("Rust Panicks here!");
}


Output:

 

Explanation:

Here, when the panic! macro is called then the error details are shown i.e. in the 2nd line 5th character. The first line in the code shows the user the panic message and then places our source code in the place where the panic occurred.

Example 2:

Rust




fn main() {
    let var = vec![10, 20, 30, 40, 50];
  
    var[100];
}


Output:

 

Explanation:

In this example, we are trying to pass the 100th element in our vector var. As our vector has only 5 elements, therefore it panics and hence returns the error message ‘index out of bounds’.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads