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’.
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
29 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...