0
0
Rustprogramming~5 mins

Propagating errors with ? in Rust - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the ? operator do in Rust?
It checks if a function returned an error. If there is an error, it returns it immediately from the current function. Otherwise, it continues with the successful value.
Click to reveal answer
beginner
How does ? help with error propagation?
It lets you write less code by automatically returning errors up the call stack without needing explicit match or if let statements.
Click to reveal answer
intermediate
Can ? be used in functions that do not return a Result or Option?
No. The function must return a compatible type like Result or Option for ? to work.
Click to reveal answer
beginner
Example: What does this code do?<br><pre>let file = std::fs::File::open("foo.txt")?;</pre>
It tries to open the file "foo.txt". If it fails, the error is returned from the current function immediately. If it succeeds, the file handle is stored in file.
Click to reveal answer
intermediate
Why is using ? considered more readable than manual error handling?
Because it reduces nested code and boilerplate, making the main logic clearer and easier to follow.
Click to reveal answer
What happens when ? encounters an error in a Result?
AIt returns the error from the current function immediately.
BIt ignores the error and continues.
CIt panics and stops the program.
DIt converts the error to a string.
Which return types are compatible with using ??
AOnly <code>Result</code> and <code>Option</code>.
BAny type.
COnly <code>String</code>.
DOnly <code>bool</code>.
What is the main benefit of using ? in Rust?
AConverts errors to warnings.
BMakes the program run faster.
CAutomatically fixes errors.
DSimplifies error handling by reducing boilerplate.
Can you use ? inside a function that returns void (unit type)?
AOnly if you import a special crate.
BYes, always.
CNo, the function must return <code>Result</code> or <code>Option</code>.
DOnly in async functions.
What does this code do?<br>
let content = std::fs::read_to_string("file.txt")?;
APrints the file content to the screen.
BReads the file content or returns an error immediately.
CIgnores any errors and returns empty string.
DCreates a new file named "file.txt".
Explain how the ? operator helps with error propagation in Rust.
Think about how errors move up the call stack without extra code.
You got /4 concepts.
    Describe a simple example where using ? makes your Rust code easier to read.
    Imagine you want to open a file and return an error if it fails.
    You got /4 concepts.