FAQ - Help and questions

How do Java checked exceptions and exception hierarchies map to Rust errors?

#porting#java#error-handlingpublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

A method that throws a checked exception returns a Result in Rust, and the exception class hierarchy becomes one enum with a variant per kind of failure. The question mark operator replaces propagation, From replaces wrapping, and the source method replaces getCause. Only panic escapes the type.

Checked with rustc 1.93.0, OpenJDK 17.0.18, Windows 11

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

#1

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 ?.

JavaRust
class ConfigException extends Exceptionan 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 bugspanic!, unwrap, expect (see the thread on panics and errors)
finally / try-with-resourcesDrop (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):

java
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: Cy

The Rust side defines the error type once, with the cause kept for source(), and ? does the propagation:

src/main.rsrust
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})");
            }
        }
    }
}
text
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#

  1. For each Java method with throws, change the return type to Result<T, YourError>.
  2. Make one error enum per module (not one per class). Each variant is one catch branch of the old code.
  3. Replace throw with return Err(..), and each call that can fail with the call followed by ?.
  4. To wrap a lower-level error (the cause argument), add a From<LowerError> implementation. ? then converts automatically. The code above uses map_err where it needs to add the key name.
  5. 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 used throws. 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.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet