Answer#
Java makes the possible failures part of a method's signature when they are checked exceptions (throws NotFound), and leaves them out for runtime exceptions. Rust makes every recoverable failure part of the return type: Result<T, E>. A caller cannot ignore it by accident, because the value is not the T until it has been handled or passed on with ?.
| Java | Rust |
|---|---|
class ConfigException extends Exception | an enum ConfigError with a variant per cause |
throws IOException | -> Result<T, io::Error> |
throw new X(...) | return Err(X...) |
| propagating by not catching | ? after the call |
catch (A e) { } catch (B e) { } | match on the error value |
new X("msg", cause) and getCause() | a field holding the cause, and Error::source() |
RuntimeException for bugs | panic!, unwrap, expect (see the thread on panics and errors) |
finally / try-with-resources | Drop (see the thread on using and try-with-resources) |
The Java side, as it was compiled and run with OpenJDK 17.0.18 (a lookup that throws a checked exception):
static class NotFound extends Exception { NotFound(String n) { super(n); } }
static int findAge(Map<String, Integer> ages, String name) throws NotFound {
Integer a = ages.get(name);
if (a == null) throw new NotFound(name);
return a;
}
// try { findAge(ages, "Cy"); } catch (NotFound e) { System.out.println("not found: " + e.getMessage()); }
// prints: not found: CyThe Rust side defines the error type once, with the cause kept for source(), and ? does the propagation:
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
BadNumber { key: String, source: ParseIntError },
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ConfigError::Missing(k) => write!(f, "missing key {k}"),
ConfigError::BadNumber { key, .. } => write!(f, "key {key} is not a number"),
}
}
}
impl std::error::Error for ConfigError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConfigError::BadNumber { source, .. } => Some(source),
_ => None,
}
}
}
fn get_port(pairs: &[(&str, &str)]) -> Result<u16, ConfigError> {
let raw = pairs.iter().find(|(k, _)| *k == "port").map(|(_, v)| *v).ok_or_else(|| ConfigError::Missing("port".into()))?;
raw.parse::<u16>().map_err(|e| ConfigError::BadNumber { key: "port".into(), source: e })
}
fn main() {
for case in [vec![("port", "8080")], vec![], vec![("port", "http")], vec![("port", "70000")]] {
match get_port(&case) {
Ok(p) => println!("ok {p}"),
Err(e) => {
let cause = std::error::Error::source(&e).map(|s| s.to_string()).unwrap_or_default();
println!("error: {e} (cause: {cause})");
}
}
}
}ok 8080
error: missing key port (cause: )
error: key port is not a number (cause: invalid digit found in string)
error: key port is not a number (cause: number too large to fit in target type)One enum replaces the class hierarchy because the set of failures of one function or module is known when you write it. Callers that care about one case match it; callers that do not care pass it up with ?.
How to do it#
- For each Java method with
throws, change the return type toResult<T, YourError>. - Make one error enum per module (not one per class). Each variant is one
catchbranch of the old code. - Replace
throwwithreturn Err(..), and each call that can fail with the call followed by?. - To wrap a lower-level error (the
causeargument), add aFrom<LowerError>implementation.?then converts automatically. The code above usesmap_errwhere it needs to add the key name. - In an application (not a library) where callers only print errors,
Box<dyn std::error::Error>as the error type saves writing an enum.
Common mistakes#
- Using
unwrap()where Java usedthrows. It turns a handled failure into a crash. - Porting every exception subclass to its own struct. A single enum is easier to match on.
- Losing the cause. If you replace the error with a message string,
source()has nothing to return and the original reason is gone.
Related questions#
What replaces a catch-all catch (Exception e)?#
A match arm with a wildcard (Err(e) => ...) at the place where you decide to report or log. Do it at the edge of the program (a request handler or main), not deep inside.
Do I need a crate for this?#
No: the example uses only the standard library. Crates such as thiserror and anyhow reduce the typing; they are optional.
Sources#
- The Rust Book, "Recoverable Errors with Result": https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html
std::error::Error: https://doc.rust-lang.org/std/error/trait.Error.html