Rust Error Handling Quiz

Rust
0 Passed
0% acceptance

Master Rust's robust error handling system with Result, Option, and the ? operator for reliable code

40 Questions
~80 minutes
1

Question 1

What is the Result type in Rust?

A
An enum representing either success (Ok) or failure (Err)
B
A type for optional values
C
A type for collections
D
Result doesn't exist
2

Question 2

What does this Result example show?

rust
fn divide(a: i32, b: i32) -> Result<i32, String> {
    if b == 0 {
        Err(String::from("Division by zero"))
    } else {
        Ok(a / b)
    }
}
A
Function returns Result with success value or error message
B
Compilation error
C
Function always succeeds
D
Runtime error
3

Question 3

What is the Option type?

A
An enum representing Some(value) or None for absence
B
A type for errors
C
A type for collections
D
Option doesn't exist
4

Question 4

What does this Option example show?

rust
fn find_first_even(nums: &[i32]) -> Option<i32> {
    for &num in nums {
        if num % 2 == 0 {
            return Some(num);
        }
    }
    None
}
A
Returns Some(first_even) or None if no even numbers found
B
Compilation error
C
Always returns Some value
D
Runtime error
5

Question 5

What is the ? operator used for?

A
Early return with error propagation from Result/Option
B
Unwrapping values
C
Creating errors
D
? operator doesn't exist
6

Question 6

What does this ? operator example do?

rust
fn read_file() -> Result<String, std::io::Error> {
    let content = std::fs::read_to_string("file.txt")?;
    Ok(content)
}
A
Returns error if file reading fails, otherwise returns content
B
Compilation error
C
Always succeeds
D
Runtime error
7

Question 7

What is the difference between unwrap() and expect()?

A
expect() provides custom panic message, unwrap() uses default
B
unwrap() is safer than expect()
C
They are identical
D
Neither exists
8

Question 8

When should you use unwrap() or expect()?

A
When you're certain the value exists and want to panic otherwise
B
For all error handling
C
When you want to ignore errors
D
Never, they're always wrong
9

Question 9

What does the map() method do on Result?

A
Transforms the Ok value if present
B
Transforms the Err value
C
Always returns Ok
D
map() doesn't exist on Result
10

Question 10

What does this Result map() example do?

rust
let result: Result<i32, &str> = Ok(5);
let doubled = result.map(|x| x * 2);
A
doubled is Ok(10), applying function to success value
B
Compilation error
C
doubled is Ok(5)
D
Runtime error
11

Question 11

What does map_err() do?

A
Transforms the error value in a Result
B
Transforms the success value
C
Always returns Err
D
map_err() doesn't exist
12

Question 12

What does this map_err() example do?

rust
let result: Result<i32, &str> = Err("error");
let mapped = result.map_err(|e| format!("Error: {}", e));
A
mapped is Err("Error: error"), transforming error message
B
Compilation error
C
mapped is Ok value
D
Runtime error
13

Question 13

What does and_then() do?

A
Chains operations that return Result, short-circuiting on error
B
Always executes both operations
C
Combines two Results
D
and_then() doesn't exist
14

Question 14

What does this and_then() example do?

rust
let result = Ok(5).and_then(|x| Ok(x * 2));
A
result is Ok(10), chaining successful operations
B
Compilation error
C
result is Ok(5)
D
Runtime error
15

Question 15

What does or_else() do?

A
Provides fallback for Err case, returns Result
B
Provides fallback for Ok case
C
Always returns Ok
D
or_else() doesn't exist
16

Question 16

What does unwrap_or() do for Option?

A
Returns inner value or provided default if None
B
Always panics
C
Returns None
D
unwrap_or() doesn't exist
17

Question 17

What does this unwrap_or() example return?

rust
let option: Option<i32> = None;
let value = option.unwrap_or(42);
A
42, using the default value
B
Compilation error
C
Panics
D
0
18

Question 18

What does unwrap_or_else() do?

A
Calls closure to provide default value if None
B
Always calls the closure
C
Never calls the closure
D
unwrap_or_else() doesn't exist
19

Question 19

What is a custom error enum?

A
User-defined enum implementing std::error::Error for rich error types
B
Built-in error type
C
Error without variants
D
Custom error enums don't exist
20

Question 20

What does this custom error enum example show?

rust
#[derive(Debug)]
enum MyError {
    Io(std::io::Error),
    Parse(std::num::ParseIntError),
    Custom(String),
}
A
Enum wrapping different error types for unified error handling
B
Compilation error
C
Single error type
D
Runtime error
21

Question 21

How do you implement std::error::Error for custom errors?

A
Implement Error, Display, and Debug traits
B
Only implement Error trait
C
Use derive macro
D
No implementation needed
22

Question 22

What is the From trait used for in error handling?

A
Automatic conversion between error types
B
Creating errors
C
Displaying errors
D
From trait isn't used for errors
23

Question 23

What does this From implementation enable?

rust
impl From<std::io::Error> for MyError {
    fn from(error: std::io::Error) -> Self {
        MyError::Io(error)
    }
}
A
? operator can convert io::Error to MyError automatically
B
Compilation error
C
Manual conversion only
D
Runtime error
24

Question 24

What is the Box<dyn std::error::Error> pattern?

A
Trait object allowing any error type that implements Error
B
Boxed error values
C
Error without type information
D
This pattern doesn't exist
25

Question 25

What does this Box<dyn Error> example show?

rust
fn dynamic_error() -> Result<(), Box<dyn std::error::Error>> {
    Err(Box::new(std::io::Error::new(std::io::ErrorKind::Other, "error")))
}
A
Function can return any error type through trait object
B
Compilation error
C
Specific error type only
D
Runtime error
26

Question 26

What is error propagation?

A
Passing errors up the call stack using ? or manual returns
B
Ignoring errors
C
Converting errors
D
Error propagation doesn't exist
27

Question 27

What does this error propagation example show?

rust
fn outer() -> Result<(), std::io::Error> {
    inner()?;
    Ok(())
}

fn inner() -> Result<(), std::io::Error> {
    Err(std::io::Error::new(std::io::ErrorKind::Other, "error"))
}
A
Error from inner() propagates to outer() via ?
B
Compilation error
C
No error propagation
D
Runtime error
28

Question 28

What is the difference between panic! and returning Result?

A
panic! is for unrecoverable errors, Result for recoverable ones
B
They are identical
C
Result is for unrecoverable errors
D
panic! doesn't exist
29

Question 29

What is the Result<T, E> syntax sugar?

A
Result<!, E> means Result<(), E> for functions returning only errors
B
Result<T, !> means infallible operations
C
Both A and B
D
No syntax sugar exists
30

Question 30

What does Ok(()) represent?

A
Success with no meaningful return value
B
Error condition
C
Empty Result
D
Ok(()) doesn't make sense
31

Question 31

What is the try! macro?

A
Older version of ? operator for error propagation
B
Macro for trying operations
C
Macro for creating Results
D
try! doesn't exist
32

Question 32

What does this pattern matching on Result show?

rust
match divide(10, 2) {
    Ok(result) => println!("Result: {}", result),
    Err(error) => println!("Error: {}", error),
}
A
Explicit handling of both success and error cases
B
Compilation error
C
Only handles success
D
Runtime error
33

Question 33

What does if let work with Results?

rust
if let Ok(value) = divide(10, 2) {
    println!("Success: {}", value);
}
A
Conditionally executes code only on success
B
Compilation error
C
Always executes
D
Runtime error
34

Question 34

What is error chaining?

A
Using ? operator to propagate errors through multiple function calls
B
Linking error types together
C
Creating error chains manually
D
Error chaining doesn't exist
35

Question 35

What does this error chaining example show?

rust
fn complex_operation() -> Result<i32, std::io::Error> {
    let file = std::fs::File::open("data.txt")?;
    let content = read_content(file)?;
    let result = parse_number(content)?;
    Ok(result)
}
A
Any step failing causes early return with error
B
Compilation error
C
All operations always succeed
D
Runtime error
36

Question 36

What is the main advantage of Result over exceptions?

A
Errors are explicit in function signatures, compiler enforces handling
B
Result is faster than exceptions
C
Result uses less memory
D
No advantages
37

Question 37

What is the main advantage of Option over null?

A
Type system forces checking for None before use
B
Option is faster than null
C
Option uses less memory
D
No advantages
38

Question 38

What does expect() do differently from unwrap()?

rust
let value = Some(5).expect("Value should exist");
A
Provides custom panic message: 'Value should exist'
B
Compilation error
C
Same as unwrap()
D
Runtime error
39

Question 39

What is error downcasting?

A
Converting Box<dyn Error> back to concrete error types
B
Converting errors to strings
C
Ignoring errors
D
Error downcasting doesn't exist
40

Question 40

In a complex application where you have multiple layers (database, business logic, API), how should you handle errors to maintain good separation of concerns while providing meaningful error messages to users?

A
Use custom error enums at each layer with From implementations, map errors to user-friendly messages at API boundary
B
Use String for all errors to keep it simple
C
Panic at every layer for immediate failure
D
Use unwrap() everywhere and handle panics globally

QUIZZES IN Rust