Rust errors: Difference between revisions

From wikinotes
Line 21: Line 21:
= Result =
= Result =
<blockquote>
<blockquote>
The result type is an enum, whose options <code>Ok, Err</code> have been merged into the global scope through <code>prelude</code>.  
The result type is an enum, whose options <code>Ok, Err</code> have been merged into the global scope through <code>prelude</code>.


Example.
Example.
<syntaxhighlight lang="rust">
<syntaxhighlight lang="rust">
fn is_one(i: isize) -> Result<String, String> {
struct MyError {
    value: isize
}
 
fn is_one(i: isize) -> Result<String, MyError> {
     if i == 1 {
     if i == 1 {
         Ok("success".to_string())
         Ok("success".to_string())


     } else {
     } else {
         Err("not success".to_string())
         Err(MyError{value: i})
     }
     }
}
}


fn main() {
</syntaxhighlight>
    let result = match is_one(2) {
 
        Ok(x) => format!("horay: {}", x),
You can treat this like Option using <code>match</code>:
        Err(x) => format!("[ERROR] {}", x),
<syntaxhighlight lang="rust">
    };
let result = match is_one(2) {
    println!("{}", result);
    Ok(x) => format!("horay: {}", x),
}
    Err(_) => panic!("an error occurred")
};
println!("{}", result);
</syntaxhighlight>
 
But there are more concise ways of handling this
<syntaxhighlight lang="rust">
// panic if error, otherwise return value
let result = is_one(2)
    .unwrap()


// panic with message if error, otherwise return value
let result = is_one(2)
    .expect("an error occurred!")  // <-- panic message
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Result -->
</blockquote><!-- Result -->

Revision as of 18:11, 8 February 2023

Rust has two primary methods of handling errors.

  • panic!() halts/exits the program
  • Result types are for handle-able errors

panic

  • intended for halting application, not control flow
  • have backtraces
panic!("tried to X but couldn't Y")

// convert panic to result
// (not intended for native rust code)
let result = panic::catch_unwind(|| {
    panic!("oh no!");
});

Result

The result type is an enum, whose options Ok, Err have been merged into the global scope through prelude.

Example.

struct MyError {
    value: isize
}

fn is_one(i: isize) -> Result<String, MyError> {
    if i == 1 {
        Ok("success".to_string())

    } else {
        Err(MyError{value: i})
    }
}

You can treat this like Option using match:

let result = match is_one(2) {
    Ok(x) => format!("horay: {}", x),
    Err(_) => panic!("an error occurred")
};
println!("{}", result);

But there are more concise ways of handling this

// panic if error, otherwise return value
let result = is_one(2)
    .unwrap()

// panic with message if error, otherwise return value
let result = is_one(2)
    .expect("an error occurred!")  // <-- panic message