Difference between revisions of "Rust-Programming-Language/C2/Error-Handling/English"

From Script | Spoken-Tutorial
Jump to: navigation, search
(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...")
 
 
Line 5: Line 5:
 
|-
 
|-
 
|| '''Slide 1'''
 
|| '''Slide 1'''
|| <span style="color:#000000;">Welcome to the Spoken Tutorial on </span><span style="color:#000000;">'''Error handling'''</span><span style="color:#000000;"> in </span><span style="color:#000000;">'''Rust.'''</span>
+
|| Welcome to the Spoken Tutorial on '''Error handling''' in'''Rust.'''
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">'''Slide 2'''</div>
+
|| '''Slide 2'''
  
<div style="color:#000000;">'''Learning Objectives'''</div>
+
'''Learning Objectives'''
 
|| In this tutorial, we will learn about:
 
|| In this tutorial, we will learn about:
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">Recoverable Errors </div>
+
* Recoverable Errors  
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">Unrecoverable Errors and</div>
+
* Unrecoverable Errors and
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">Error Propagation Operator</div>
+
* Error Propagation Operator
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">'''Slide 3'''</div>
+
|| '''Slide 3'''
  
<div style="color:#000000;">'''System Requirements'''</div>
+
'''System Requirements'''
  
 
|| To record this tutorial I’m using the following setup.
 
|| To record this tutorial I’m using the following setup.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">'''Slide'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''5'''</span>
+
|| '''Slide 4'''
  
<div style="color:#000000;">'''Code Files'''</div>
+
'''Code Files'''
 
||
 
||
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">The following code file is required to practise this tutorial.</div>
+
* The following code file is required to practise this tutorial.
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">This file is provided in the Code Files link of this tutorial page.</div>
+
* This file is provided in the Code Files link of this tutorial page.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.101cm;padding-right:0.191cm;"
+
|-  
|| <span style="color:#000000;">'''Slide</span> 6'''
+
|| '''Slide 5'''
  
 
'''Types of Errors'''
 
'''Types of Errors'''
 
|| In Rust, errors are categorized as
 
|| In Rust, errors are categorized as
  
<span style="color:#000000;">1. </span><span style="color:#000000;">'''Recoverable Errors'''</span><span style="color:#000000;"> →These are anticipated failures, handled with </span><span style="color:#188038;">Option</span><span style="color:#000000;"> and </span><span style="color:#188038;">Result</span><span style="color:#000000;"> enums</span>
+
1.'''Recoverable Errors''' → These are anticipated failures, handled with '''Option''' and '''Result enums'''.
  
<span style="color:#000000;">2. </span><span style="color:#000000;">'''Unrecoverable Errors'''</span><span style="color:#000000;"> → These are unexpected </span>critical<span style="color:#000000;"> failures. </span>They lead<span style="color:#000000;"> to a </span><span style="color:#000000;">'''panic!'''</span><span style="color:#000000;"> and program termination.</span>
+
2.'''Unrecoverable Errors''' → These are unexpected critical failures.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| <span style="color:#000000;">Open </span><span style="color:#000000;">'''Visual'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''code editor'''</span>
+
|| <span style="color:#000000;">Open the </span><span style="color:#000000;">'''Visual </span><span style="color:#000000;">S</span><span style="color:#000000;">tudio code editor.'''</span>
+
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| <span style="color:#000000;">In the menu bar, click on </span><span style="color:#000000;">'''Terminal'''</span><span style="color:#000000;"> and select</span><span style="color:#000000;">''' New Terminal'''</span><span style="color:#000000;">.</span>
+
  
|| <span style="color:#000000;">In the menu bar, click on </span><span style="color:#000000;">'''Terminal'''</span><span style="color:#000000;"> and select</span><span style="color:#000000;">''' New Terminal'''</span><span style="color:#000000;">.</span>
+
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'''.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| In the menu bar, click on '''Terminal''' and select ''' New Terminal'''.
|| <span style="color:#000000;">'''> cd'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''Desktop'''</span><span style="color:#000000;">/</span><span style="color:#000000;">'''MyRustProject'''</span>
+
  
<span style="color:#000000;">'''>'''</span><span style="color:#000000;"> </span><span style="color:#000000;">'''cargo new errorhandling'''</span>
+
|-
 +
|| '''> cd''''''Desktop'''/'''MyRustProject'''
  
<div style="color:#000000;">'''In the menu bar, File >> Open folder >> Desktop >> MyRustProject >> errorhandling'''</div>
+
'''>''''''cargo new errorhandling'''
|| <span style="color:#000000;">Let us go to our working directory </span><span style="color:#000000;">'''MyRustProject'''</span><span style="color:#000000;"> as explained earlier.</span>
+
  
<span style="color:#000000;">Type the command </span><span style="color:#000000;">'''cargo new errorhandling '''</span><span style="color:#000000;">and press </span><span style="color:#000000;">'''Enter.'''</span>
+
'''In the menu bar, File >> Open folder.
  
<div style="color:#000000;">Open the created project as shown.</div>
+
>> Desktop >> MyRustProject >> errorhandling'''
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| <span style="color:#000000;">Point to the </span><span style="color:#000000;">'''main.rs'''</span><span style="color:#000000;"> file.</span>
+
  
|| <span style="background-color:#ffffff;color:#000000;">In the </span><span style="background-color:#ffffff;color:#000000;">'''main.rs '''</span><span style="background-color:#ffffff;color:#000000;">file, copy and paste the code from the Code file.</span>
+
|| Let us go to our working directory '''MyRustProject''' as explained earlier.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| <div style="color:#000000;">fn divide(x: f64, y: f64) -> Result<f64, String> {</div>
+
  
<div style="color:#000000;">if y == 0.0 {</div>
+
Type the command '''cargo new errorhandling ''' and press'''Enter.'''
  
<div style="color:#000000;">Err(String::from("Cannot divide by zero"))</div>
+
Open the created project as shown.
 +
|-
 +
|| Point to the'''main.rs''' file.
  
<div style="color:#000000;">} else {</div>
+
|| In the '''main.rs ''' file, copy and paste the code from the Code file.
 +
|-
 +
|| fn divide(x: f64, y: f64) -> Result<f64, String> {
  
<div style="color:#000000;">Ok(x / y)</div>
+
if y == 0.0 {
  
<div style="color:#000000;">}</div>
+
Err(String::from("Cannot divide by zero"))
  
<div style="color:#000000;">}</div>
+
} else {
  
<div style="color:#000000;">fn main(){</div>
+
Ok(x / y)
  
<div style="color:#000000;">match divide(10.0, 0.0) {</div>
+
}
  
<div style="color:#000000;">Ok(result) => println!("Result: {}", result),</div>
+
}
  
<div style="color:#000000;">Err(e) => println!("Error: {}", e),</div>
+
fn main(){
  
<div style="color:#000000;">}</div>
+
match divide(10.0, 0.0) {
  
<div style="color:#000000;">}</div>
+
Ok(result) => println!("Result: {}", result),
|| <div style="color:#000000;">This program explains about recoverable errors.</div>
+
  
<span style="color:#000000;">Function </span><span style="color:#188038;">divide</span><span style="color:#000000;"> takes two integers as input parameters and returns the division result.</span>
+
Err(e) => println!("Error: {}", e),
  
<div style="color:#000000;">What happens if we try to divide an integer by zero without handling it?</div>
+
}
  
<div style="color:#000000;">In Rust, it will cause the program to crash at runtime.</div>
+
}
 +
|| This program explains about recoverable errors.
  
D<span style="color:#000000;">ividing by zero is a known and anticipated failure.</span>
+
Function divide takes two integers as input parameters and returns the division result.
  
So<span style="color:#000000;"> we</span> <span style="color:#000000;">handle it using the </span><span style="color:#188038;">Result</span><span style="color:#000000;"> enum: </span>
+
What happens if we try to divide an integer by zero without handling it?
  
<span style="color:#000000;">If the denominator </span><span style="color:#188038;">y</span><span style="color:#000000;"> is </span><span style="color:#188038;">0</span><span style="color:#000000;">, function returns an </span><span style="color:#188038;">Err</span><span style="color:#000000;"> containing an error message.</span>
+
In Rust, it will cause the program to crash at runtime.
  
<span style="color:#000000;">If the denominator is valid, </span><span style="color:#000000;">function returns the successful division wrapped in </span><span style="color:#188038;">Ok</span><span style="color:#000000;">.</span>
+
Dividing by zero is a known and anticipated failure.
  
<div style="color:#000000;">Save the program.</div>
+
So we handle it using the '''Result enum'''.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
| style="color:#000000;" |
+
|| 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.
+
If the denominator y is 0, function returns an '''Err''' containing an error message.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
 
| style="color:#252525;" |  
+
If the denominator is valid, function returns the successful division wrapped in '''Ok'''.
 +
 
 +
Save the program.
 +
|-
 +
|| In the terminal, type '''cargo run '''.
 +
|| 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.
 
|| Next let us see an example of an unexpected error.
  
 
Clear the code and Copy paste the code from the code file.
 
Clear the code and Copy paste the code from the code file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">fn main() {</div>
+
|| fn main() {
  
<div style="color:#000000;">let v = vec![1, 2, 3];</div>
+
let v = vec![1, 2, 3];
  
<div style="color:#000000;">println!("{}", v[99]); // panics: index out of bounds</div>
+
println!("{}", v[99]); // panics: index out of bounds
  
<div style="color:#000000;">panic!("Something went terribly wrong!");</div>
+
panic!("Something went terribly wrong!");
  
 
}
 
}
  
|| <div style="color:#000000;">What happens when the program encounters an unexpected error?</div>
+
|| What happens when the program encounters an unexpected error?
  
<div style="color:#000000;">That is something we do not anticipate and cannot recover from.</div>
+
That is something we do not anticipate and cannot recover from.
  
We have declared a vector v with three elements.
+
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'''.
+
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.
+
After a panic, the program '''stops execution''', it does not continue to the next line.
  
<div style="color:#000000;">Save the program.</div>
+
Save the program.
  
<div style="color:#252525;">Let us run the program</div>
+
Let us run the program
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#252525;"></div>
+
|| In the terminal, type '''cargo run'''.
 
+
|| In the terminal, type '''cargo run'''.
<div style="color:#252525;"></div>
+
 
+
<div style="color:#ff0000;"></div>
+
|| <span style="color:#000000;">In the term</span>inal, type '''cargo run'''
+
  
 
The program prints an error message and the current thread stops.
 
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.
 
The panic statement is not executed because the program already panics at the previous line.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#252525;" |  
+
||  
 
|| Next we will see about the Error Propagation operator.
 
|| Next we will see about the Error Propagation operator.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#000000;">Slide:</div>
+
|| '''Slide 6''':
  
<div style="color:#000000;">Error Propagation Operator (?)</div>
+
'''Error Propagation Operator (?)'''
 
||
 
||
* <div style="color:#000000;margin-left:1.27cm;margin-right:0cm;">Error Propagation Operator (?} automatically returns an error if a function call fails.</div>
+
* Error Propagation Operator (?} automatically returns an error if a function call fails.
* <div style="margin-left:1.27cm;margin-right:0cm;"><span style="color:#000000;">This operator can be only used in functions where it returns </span><span style="color:#000000;">'''option '''</span><span style="color:#000000;">or </span><span style="color:#000000;">'''result enum.'''</span></div>
+
* This operator can be only used in functions where it returns '''option ''' or '''result enum'''.
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
||  
|| Switch<span style="color:#000000;"> back to the visual code editor.</span>
+
|| Switch back to the '''visual code editor'''.
  
<div style="color:#000000;">Copy and paste the code from the code file</div>
+
Copy and paste the code from the code file.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
|| <div style="color:#252525;">use std::fs::File;</div>
+
|| use std::fs::File;
  
<div style="color:#252525;">use std::io::{self, Read};</div>
+
use std::io::{self, Read};
  
<div style="color:#252525;">fn read_file(filename: &str) -> Result<String, io::Error> {</div>
+
fn read_file(filename: &str) -> Result<String, io::Error> {
  
<div style="color:#252525;">let mut file = File::open(filename)?;// This will return early if File::open fails</div>
+
let mut file = File::open(filename)?;// This will return early if File::open fails
  
<div style="color:#252525;">let mut contents = String::new();</div>
+
let mut contents = String::new();
  
<div style="color:#252525;">file.read_to_string(&mut contents)?;// This will return early if read_to_string fails</div>
+
file.read_to_string(&mut contents)?;// This will return early if read_to_string fails
  
<div style="color:#252525;">Ok(contents)</div>
+
Ok(contents)
  
<div style="color:#252525;">}</div>
+
}
  
<div style="color:#252525;">fn main() {</div>
+
fn main() {
  
<div style="color:#252525;">match read_file("hello.txt") {</div>
+
match read_file("hello.txt") {
  
<div style="color:#252525;">Ok(content) => println!("File content: {}", content),</div>
+
Ok(content) => println!("File content: {}", content),
  
<div style="color:#252525;">Err(e) => println!("Error reading file: {}", e),</div>
+
Err(e) => println!("Error reading file: {}", e),
  
<div style="color:#252525;">}</div>
+
}
  
<div style="color:#252525;">}</div>
+
}
  
|| <div style="color:#000000;"></div>
+
|| In this example we try to read the file contents and return the '''Result enum.'''
  
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.
  
<span style="color:#252525;">The </span><span style="color:#252525;">'''read_file'''</span><span style="color:#252525;"> takes a filename which is of type string slice.</span>
+
It returns a '''Result enum''' with '''Ok type'''  as String and '''Err type''' as input output error.
  
<span style="color:#252525;">It returns a </span><span style="color:#252525;">'''Result enum'''</span><span style="color:#252525;"> with </span><span style="color:#252525;">'''Ok'''</span><span style="color:#252525;"> </span><span style="color:#252525;">'''type'''</span><span style="color:#252525;"> </span><span style="color:#252525;">as</span><span style="color:#252525;"> String and </span><span style="color:#252525;">'''Err'''</span><span style="color:#252525;"> </span><span style="color:#252525;">'''type'''</span><span style="color:#252525;"> as</span><span style="color:#252525;"> input output error.</span>
+
At the line '''File::open(filename)?,''' error propagation operator, it attempts to open the file, with the  error propagation operator(?).
  
<span style="color:#252525;">At the line </span><span style="color:#252525;">'''File::open(filename)?,'''</span><span style="color:#252525;"> it attempts to open the file, with the ? operator</span>
+
If successful, it continues execution with the file handle.
  
<div style="color:#252525;">If successful, it continues execution with the file handle.</div>
+
If it fails, it returns the error from the function.
  
<span style="color:#252525;">If it fail</span><span style="color:#252525;">s</span><span style="color:#252525;">, it returns the error from the function.</span>
+
Next we initialise  a mutable variable called'''contents'''.
  
<span style="color:#252525;">Next we initialised a mutable variable called </span><span style="color:#252525;">'''contents'''</span><span style="color:#252525;">.</span>
+
It is of the type'''String''' object.
  
<span style="color:#252525;">It is of the type </span><span style="color:#252525;">'''String'''</span><span style="color:#252525;"> object.</span>
+
'''read_to_string''' reads all the bytes of the file till end and appends them to '''contents.'''
  
<span style="color:#252525;">'''read_to_string'''</span><span style="color:#252525;"> reads all the bytes of the file till </span><span style="color:#252525;">e</span><span style="color:#252525;">nd and </span><span style="color:#252525;">appends them to </span><span style="color:#252525;">'''contents.'''</span>
+
The error propagation(?) Operator returns the error immediately if it fails.
  
<span style="color:#252525;">The ? Operator returns the error </span><span style="color:#252525;">immediately if</span><span style="color:#252525;"> it fails.</span>
+
If everything succeeds, it returns the file content.
  
<span style="color:#252525;">If everything succeeds, it </span><span style="color:#252525;">returns</span><span style="color:#252525;"> the file content.</span>
+
In main function, we use '''match''' arms to handle results returned by'''read_file''' function.
  
<span style="color:#252525;">In main function, we use </span><span style="color:#252525;">'''match'''</span><span style="color:#252525;"> arms to handle </span><span style="color:#252525;">results</span><span style="color:#252525;"> returned </span><span style="color:#252525;">by </span><span style="color:#252525;">'''read_file'''</span><span style="color:#252525;"> function.</span>
+
Save the program.
 
+
|-  
<div style="color:#000000;">Save the program.</div>
+
|| In the terminal, type '''cargo run'''.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| In the terminal, type '''cargo run'''.
| style="color:#000000;" |  
+
|| <span style="color:#000000;">In the terminal, type </span><span style="color:#000000;">'''cargo run'''</span>
+
  
 
We can see the error message “Error reading file”.
 
We can see the error message “Error reading file”.
  
 
This shows that the file '''hello.txt''' is not available.
 
This shows that the file '''hello.txt''' is not available.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" |  
+
|| '''Slide 7'''
|| <div style="color:#000000;">This brings us to the end of this tutorial.</div>
+
'''
 
+
Summary'''
<div style="color:#000000;">Let us summarize. </div>
+
|| This brings us to the end of this tutorial.
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|| <div style="color:#000000;">'''Slide 8'''</div>
+
  
 +
Let us summarize.
 +
|-
 +
|| '''Slide 8'''
 
|| As an assignment, do the following
 
|| As an assignment, do the following
  
 
1. Create '''hello.txt''' file and with the text “Welcome to Rust tutorials”
 
1. Create '''hello.txt''' file and with the text “Welcome to Rust tutorials”
  
2. Save the file in the errorhandling folder
+
2. Save the file in the error handling folder
  
3. Run the <span style="color:#000000;">Error Propagation Operator program </span>and check<span style="color:#000000;"> the output</span>
+
3. Run the Error Propagation Operator program and check the output
  
|- style="border:1pt solid #000000;padding-top:0cm;padding-bottom:0cm;padding-left:0.206cm;padding-right:0.191cm;"
+
|-  
| style="color:#000000;" | '''Slide 9 Thank You'''
+
|| '''Slide 9'''
| style="color:#000000;" | Thanks for joining.
+
 +
'''Thank You'''
 +
|| Thanks for joining.
 
|-
 
|-
 
|}
 
|}
<div style="margin-left:-1.588cm;margin-right:-1.429cm;"></div>
 

Latest revision as of 17:37, 4 December 2025

Visual Cue Narration
Slide 1 Welcome to the Spoken Tutorial on Error handling inRust.
Slide 2

Learning Objectives

In this tutorial, we will learn about:
  • Recoverable Errors
  • Unrecoverable Errors and
  • Error Propagation Operator
Slide 3

System Requirements

To record this tutorial I’m using the following setup.
Slide 4

Code Files

  • The following code file is required to practise this tutorial.
  • This file is provided in the Code Files link of this tutorial page.
Slide 5

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.

OpenVisual 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 pressEnter.

Open the created project as shown.

Point to themain.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 . 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. 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 6:

Error Propagation Operator (?)

  • Error Propagation Operator (?} automatically returns an error if a function call fails.
  • This operator can be only used in functions where it returns option or result enum.
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)?, error propagation operator, it attempts to open the file, with the error propagation operator(?).

If successful, it continues execution with the file handle.

If it fails, it returns the error from the function.

Next we initialise a mutable variable calledcontents.

It is of the typeString object.

read_to_string reads all the bytes of the file till end and appends them to contents.

The error propagation(?) 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 byread_file function.

Save the program.

In the terminal, type cargo run. 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.

Slide 7

Summary

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 error handling folder

3. Run the Error Propagation Operator program and check the output

Slide 9

Thank You

Thanks for joining.

Contributors and Content Editors

Madhurig, Nirmala Venkat