An error is basically an unexpected behavior or event that may lead a program to produce undesired output or terminate abruptly. Errors are things that no one wants in their program. We can try to find and analyze parts of the program that can cause errors. Once we found those parts then we can define how those parts should behave if they encounter an error. This process of finding and defining cases for a particular block of code is what we call Error Handling. One thing we should keep in mind that we cannot completely get rid of errors but we can try to minimize them or at least reduce their effect on our program.
In Rust, errors can be classified into two categories namely recoverable and unrecoverable
- Recoverable Errors: Recoverable errors are those that do not cause the program to terminate abruptly. Example- When we try to fetch a file that is not present or we do not have permission to open it.
- Unrecoverable Errors: Unrecoverable errors are those that cause the program to terminate abruptly. Example- Trying to access array index greater than the size of the array.
Most language does not distinguish between the two errors and use an Exception class to overcome them while Rust uses a data type Result <R,T> to handle recoverable errors and panic! macro to stop the execution of the program in case of unrecoverable errors.
We will first see how and where should we use panic! macro. Before it, we will see what it does to a program.
Rust
fn main() {
panic!("program crashed");
}
Output:
thread 'main' panicked at 'program crashed', main.rs:2:7
So, it basically stops the execution of the program and prints what we passed it in its parameter.
panic! the macro may be in library files that we use, let us see some:
Rust
fn main() {
let v = vec![1, 2, 3];
println!("{}",v[3])
}
Output:
thread 'main' panicked at 'index out of bounds: the len is 3 but the index is 3', main.rs:3:19
Since we are trying to access elements beyond the bounds of vector therefore it called a panic! macro.
We should only use panic in a condition if our code may end up in a bad state. A bad state is when some assumption, guarantee, contract, or invariant has been broken, such as when invalid values, contradictory values, or missing values are passed to our code and at least one of the following:-
- If a bad state occurs once in a blue moon.
- Your code after this point needs to rely on not being in this bad state.
- There’s not a good way to encode this information in the types you use.
Recoverable Errors
Result<T,E> is an enum data type with two variants OK and Err which is defined something like this
enum Result<T, E> {
Ok(T),
Err(E),
}
T and E are generic type parameters where T represents the type of value that will be returned in a success case within the Ok variant, and E represents the type of error that will be returned in a failure case within the Err variant.
Rust
use std::fs::File;
fn main() {
let f = File::open("gfg.txt");
println!("{:?}",f);
}
Output:
Err(Os { code: 2, kind: NotFound, message: "No such file or directory" })
Since the file gfg.txt was not there so the Err instance was returned by File. If the file gfg.txt had been found then an instance to the file would have been returned.
If a file is not found just like the above case then it will be better if we ask the user to check the file name, file location or to give the file specifications once more or whatever the situation demands.
Rust
use std::fs::File;
fn main() {
// file doesn't exist
let f = File::open("gfg.txt");/
match f {
Ok(file)=> {
println!("file found {:?}",file);
},
Err(_error)=> {
// replace it with whatever you want
// to do if file is not found
println!("file not found \n");
}
}
}
Output:
file not found
In the above program, it basically matches the return type of the result and performs the task accordingly.
Let's create our own errors according to business logic. Suppose we want to produce an error if a person below 18 years tries to apply for voter ID.
Rust
fn main(){
let result = eligible(13);
match result {
Ok(age)=>{
println!("Person eligible to vote with age={}",age);
},
Err(msg)=>{
println!("{}",msg);
}
}
}
fn eligible(age:i32)->Result<i32,String> {
if age>=18 {
return Ok(age);
} else {
return Err("Not Eligible..Wait for some years".to_string());
}
}
Output:
Not Eligible..Wait for some years
If we want to abort the program after it encounters a recoverable error then we could use panic! macro and to simplify the process Rust provides two methods unwrap() and expect().
Rust
use std::fs::File;
fn main() {
let f = File::open("gfg.txt").unwrap();
}
Output:
thread 'main' panicked at 'called `Result::unwrap()` on an `Err` value:
Os { code: 2, kind: NotFound, message: "No such file or directory" }', main.rs:17:14
The unwrap() calls the panic! macro in case of file not found while it returns the file handler instance if the file is found. Although unwrap() makes the program shorter but when there are too many unwrap() methods in our program then it becomes a bit confusing as to which unwrap() method called the panic! macro. So we need something that can produce the customized messages. In that case, expect() method comes to the rescue.
Rust
use std::fs::File;
fn main() {
let f = File::open("hello.txt").expect("Failed to open gfg.txt");
}
Output:
thread 'main' panicked at 'Failed to open gfg.txt:
Os { code: 2, kind: NotFound, message: "No such file or directory" }', main.rs:17:14
We passed our message to panic! macro via the expected parameter.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Example of an AVL Tree:The balance factors for different nodes are : 12 :1, 8:1, 18:1, 5:1, 11:0, 17:0 and 4:0. Since all differences
4 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read