Menu
CoddyTech

Result and Propagation

Lesson 26 of 48 in Coddy's Rust for Java Developers course.

Java can report failure through checked or unchecked exceptions. Checked exceptions constrain callers through declared throws clauses; unchecked exceptions do not require such declarations. Rust Result<T, E> instead puts success or error directly in a return value. It is not an exception that automatically unwinds to a catch block. A caller can inspect Ok and Err with a match.

Inside a function returning a compatible Result, ? extracts success and returns early on error, converting the error through the available conversion relationship when needed. It does not panic and does not silently discard the failure. Rust main here handles the result explicitly, which keeps printed output predictable. The example attempts to open a logical gate and returns a small error label when it is unavailable; no resource or arithmetic task implementation is included.

Java: complete program

class Main {
    static String gate(boolean ready) throws Exception {
        if (!ready) throw new Exception("closed");
        return "open";
    }
    static String open(boolean ready) throws Exception { return gate(ready); }
    public static void main(String[] args) {
        try { System.out.println(open(false)); }
        catch (Exception e) { System.out.println("error:" + e.getMessage()); }
    }
}

Rust: complete program

fn gate(ready: bool) -> Result<&'static str, &'static str> {
    if ready { Ok("open") } else { Err("closed") }
}
fn open(ready: bool) -> Result<&'static str, &'static str> {
    let value = gate(ready)?;
    Ok(value)
}
fn main() {
    match open(false) { Ok(s) => println!("{}", s), Err(e) => println!("error:{}", e) }
}

Pitfall: ? propagates an error value through the return type. It is not equivalent to Java throwing an arbitrary exception.

challenge icon

Challenge

Easy

Implement pub fn exact_divide(a: i32, b: i32) -> Result<i32, String> and pub fn sum_quotients(pairs: &[(i32, i32)]) -> Result<i32, String> in division.rs. Division returns Err("zero") for a zero divisor, Err("fraction") for a nonzero remainder, otherwise the exact integer quotient. Sum evaluates pairs in order and returns the sum, stopping at and returning the first error; empty input is Ok(0). All inputs and intermediate values fit i32. solve reads whitespace-separated numerator/denominator pairs and returns ok:total or error:reason. The number of input integers is always even.

Implement the required exported APIs and return the result from exercise::solve(input: &str) -> String without a final newline. Do not print in editable code. The locked driver checks required APIs independently, reads all stdin, and prints the returned text with one final newline.

Your code goes in exercise.rs, division.rs. main.rs holds the supplied input/output code and cannot be edited.

Try it yourself

#![allow(dead_code, unused_imports, unused_variables, unused_mut)]
mod exercise;
mod division;
use std::io::{self, Read};
fn main() {
    let mut input=String::new();
    io::stdin().read_to_string(&mut input).unwrap();
    // BEGIN PUBLIC API PROBES
assert_eq!(division::exact_divide(35, -7), Ok(-5));
assert_eq!(division::exact_divide(0, 9), Ok(0));
assert_eq!(division::exact_divide(1, 0), Err(String::from("zero")));
assert_eq!(division::exact_divide(-8, 3), Err(String::from("fraction")));
assert_eq!(division::sum_quotients(&[(24, 6), (-15, 5)]), Ok(1));
assert_eq!(division::sum_quotients(&[]), Ok(0));
assert_eq!(division::sum_quotients(&[(7, 2), (9, 0)]), Err(String::from("fraction")));

    // END PUBLIC API PROBES
    println!("{}", exercise::solve(&input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Rust for Java Developers

Practice on your own: Online Rust compiler