0
0
Rustprogramming~10 mins

Custom error types in Rust - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a custom error enum named MyError.

Rust
#[derive(Debug)]
enum MyError {
    [1]
}
Drag options to blanks, or click blank then click option'
AIoError(std::io::Error)
BError(String)
CMyErrorType
DCustomError
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variant name without data when a message is needed
Trying to use a type name as a variant
2fill in blank
medium

Complete the code to implement the Display trait for MyError.

Rust
impl std::fmt::Display for MyError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            MyError::Error(msg) => write!(f, [1], msg),
        }
    }
}
Drag options to blanks, or click blank then click option'
A"{}"
B"MyError: {}"
C"Error: {}"
D"Error occurred: {}"
Attempts:
3 left
💡 Hint
Common Mistakes
Adding extra text that is not needed
Forgetting to include the placeholder {}
3fill in blank
hard

Fix the error in the From trait implementation to convert std::io::Error into MyError.

Rust
impl From<std::io::Error> for MyError {
    fn from(err: std::io::Error) -> MyError {
        MyError::[1](err.to_string())
    }
}
Drag options to blanks, or click blank then click option'
AIoError
BCustomError
CError
DMyErrorType
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variant name that does not exist
Passing the error type directly instead of converting to string
4fill in blank
hard

Fill in the blank to implement the std::error::Error trait for MyError.

Rust
impl std::error::Error for MyError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        [1]
    }
}
Drag options to blanks, or click blank then click option'
ANone
B"Custom error"
CSome(self)
D"MyError occurred"
Attempts:
3 left
💡 Hint
Common Mistakes
Returning Some(self) in source which causes lifetime issues
5fill in blank
hard

Fill all three blanks to create a function that returns a Result with MyError and uses the ? operator.

Rust
fn read_file(path: &str) -> Result<String, MyError> {
    let content = std::fs::read_to_string(path)[1];
    Ok([2])
}

fn main() {
    match read_file("file.txt") {
        Ok(data) => println!("File content: {}", [3]),
        Err(e) => println!("Error: {}", e),
    }
}
Drag options to blanks, or click blank then click option'
A?
Bcontent
Cdata
D.unwrap()
Attempts:
3 left
💡 Hint
Common Mistakes
Using .unwrap() which panics on error
Printing the wrong variable in main