FAQ - Help and questions

When should Rust code panic, and when should it return an error?

#error-handling#basics#reliabilitypublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Return a Result for anything that can fail because of the outside world, such as files, network, user input or configuration. Panic only for a bug, a broken internal rule that the program cannot continue from. A panic can be caught at a boundary such as one request, but only when the profile uses panic = unwind.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A Result says "this can fail, and the caller decides what to do". A panic says "the program is wrong, stop here". Input from files, networks and people will be wrong sometimes; that is not a bug, so it must be a Result.

SituationUse
A file is missing, a request is malformed, a port string is not a numberResult
An index is out of range because of a logic errorpanic (the standard indexing does this)
A value that you have just checked cannot be Noneexpect("why this cannot happen")
A test asserts a resultassert! / unwrap() is fine
src/main.rsrust
use std::panic;

fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
    s.trim().parse() // anything from outside returns a Result, no unwrap
}

fn risky(items: &[i32], i: usize) -> i32 {
    items[i] // panics when i is out of range
}

fn main() {
    println!("{:?}", parse_port("8080"));
    println!("{:?}", parse_port("eighty"));

    // A panic can be caught at a boundary (one request, one task). Works only with panic = "unwind".
    panic::set_hook(Box::new(|_| {})); // keep this demo's output short
    let r = panic::catch_unwind(|| risky(&[1, 2, 3], 7));
    println!("caught a panic: {}", r.is_err());
    let r = panic::catch_unwind(|| risky(&[1, 2, 3], 1));
    println!("no panic: {:?}", r.ok());
}
text
Ok(8080)
Err(ParseIntError { kind: InvalidDigit })
caught a panic: true
no panic: Some(2)

A server normally catches panics per request (web frameworks do this for you) so that one bug ends one request and not the whole process. If you set panic = "abort" in the release profile, a panic ends the process and nothing can catch it.

Common mistakes#

  • Using unwrap() on a Result from a file or the network in production code.
  • Using catch_unwind as a general error mechanism. It is for boundaries, not control flow.
  • Panicking in a library for bad arguments that the caller could cause; return an error, or document the panic in a # Panics section.

What does expect add over unwrap?#

A message that says why the value should be there. Use it to document an assumption, and the panic text then points at the broken assumption.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet