Difference between revisions of "Rust-Programming-Language/C2/Error-Handling/English"
(Created page with "{| border="1" |- || '''Visual Cue''' || '''Narration''' |- || '''Slide 1''' || <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#000000...") |
(No difference)
|
Revision as of 12:11, 27 October 2025
| Visual Cue | Narration |
| Slide 1 | Welcome to the Spoken Tutorial on Error handling in Rust. |
| Slide 2
Learning Objectives
|
In this tutorial, we will learn about:
|
| Slide 3
System Requirements
|
To record this tutorial I’m using the following setup. |
| Slide 5
Code Files
|
|
| Slide 6
Types of Errors |
In Rust, errors are categorized as
1. Recoverable Errors →These are anticipated failures, handled with Option and Result enums 2. Unrecoverable Errors → These are unexpected critical failures. They lead to a panic! and program termination. |
| Open Visual code editor | Open the Visual Studio code editor. |
| In the menu bar, click on Terminal and select New Terminal. | In the menu bar, click on Terminal and select New Terminal. |
| > cd Desktop/MyRustProject
> cargo new errorhandling In the menu bar, File >> Open folder >> Desktop >> MyRustProject >> errorhandling
|
Let us go to our working directory MyRustProject as explained earlier.
Type the command cargo new errorhandling and press Enter. Open the created project as shown.
|
| Point to the main.rs file. | In the main.rs file, copy and paste the code from the Code file. |
| fn divide(x: f64, y: f64) -> Result<f64, String> {
if y == 0.0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(x / y)
}
}
fn main(){
match divide(10.0, 0.0) {
Ok(result) => println!("Result: {}", result),
Err(e) => println!("Error: {}", e),
}
}
|
This program explains about recoverable errors.
Function divide takes two integers as input parameters and returns the division result. What happens if we try to divide an integer by zero without handling it?
In Rust, it will cause the program to crash at runtime.
Dividing by zero is a known and anticipated failure. So we handle it using the Result enum: If the denominator y is 0, function returns an Err containing an error message. If the denominator is valid, function returns the successful division wrapped in Ok. Save the program.
|
| In the terminal, type cargo run to see the output.
It displays the output as “Cannot divide by zero” as the denominator y is 0 in the code. | |
| Next let us see an example of an unexpected error.
Clear the code and Copy paste the code from the code file. | |
| fn main() {
let v = vec![1, 2, 3];
println!("{}", v[99]); // panics: index out of bounds
panic!("Something went terribly wrong!");
} |
What happens when the program encounters an unexpected error?
That is something we do not anticipate and cannot recover from.
We have declared a vector v with three elements. In this program, it tries to access the element at index 99, which does not exist. After a panic, the program stops execution — it does not continue to the next line. Save the program.
Let us run the program
|
| In the terminal, type cargo run
The program prints an error message and the current thread stops. The panic statement is not executed because the program already panics at the previous line. | |
| Next we will see about the Error Propagation operator. | |
| Slide:
Error Propagation Operator (?)
|
|
| Switch back to the visual code editor.
Copy and paste the code from the code file
| |
| use std::fs::File;
use std::io::{self, Read};
fn read_file(filename: &str) -> Result<String, io::Error> {
let mut file = File::open(filename)?;// This will return early if File::open fails
let mut contents = String::new();
file.read_to_string(&mut contents)?;// This will return early if read_to_string fails
Ok(contents)
}
fn main() {
match read_file("hello.txt") {
Ok(content) => println!("File content: {}", content),
Err(e) => println!("Error reading file: {}", e),
}
}
|
In this example we try to read the file contents and return the Result enum. The read_file takes a filename which is of type string slice. It returns a Result enum with Ok type as String and Err type as input output error. At the line File::open(filename)?, it attempts to open the file, with the ? operator If successful, it continues execution with the file handle.
If it fails, it returns the error from the function. Next we initialised a mutable variable called contents. It is of the type String object. read_to_string reads all the bytes of the file till end and appends them to contents. The ? Operator returns the error immediately if it fails. If everything succeeds, it returns the file content. In main function, we use match arms to handle results returned by read_file function. Save the program.
|
| In the terminal, type cargo run
We can see the error message “Error reading file”. This shows that the file hello.txt is not available. | |
| This brings us to the end of this tutorial.
Let us summarize.
| |
| Slide 8
|
As an assignment, do the following
1. Create hello.txt file and with the text “Welcome to Rust tutorials” 2. Save the file in the errorhandling folder 3. Run the Error Propagation Operator program and check the output |
| Slide 9 Thank You | Thanks for joining. |