Answer#
Python raises an exception that travels up the call stack until some except catches it, and nothing in a function's signature says which ones it may raise. Rust returns the error as part of the result, so every caller sees it, and propagating it up is one character: ?.
| Python | Rust |
|---|---|
raise ValueError("...") | return Err(MyError::...) |
try: x = f() | match f() { ... } or let x = f()?; to pass the error up |
except ValueError as e: | a match arm Err(MyError::Negative(n)) |
else: (runs when nothing was raised) | the Ok(n) arm |
finally: | a value with Drop, or code after the match |
| exception class hierarchy | an enum with a variant per kind |
assert, a bug | assert!, panic!: not for expected failures |
Both programs read a count from text. They treat empty text, non-numbers and negative numbers as three different failures, and always run a cleanup step. Python (3.13.7):
def parse_count(s):
s = s.strip()
if not s:
raise LookupError("empty")
n = int(s) # ValueError for "abc"
if n < 0:
raise ValueError(f"{n} is negative")
return n
for text in ["42", "", "abc", "-3"]:
print("input", repr(text))
try:
n = parse_count(text)
except LookupError:
print(" except: nothing to do")
except ValueError as e:
print(" except:", e)
else:
print(" else branch: got", n)
finally:
print(" finally: release the file")input '42'
else branch: got 42
finally: release the file
input ''
except: nothing to do
finally: release the file
input 'abc'
except: invalid literal for int() with base 10: 'abc'
finally: release the file
input '-3'
except: -3 is negative
finally: release the fileRust (rustc 1.93.0):
use std::fmt;
#[derive(Debug)]
enum ParseError {
Empty,
NotANumber(String),
Negative(i64),
}
impl fmt::Display for ParseError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
ParseError::Empty => write!(f, "empty input"),
ParseError::NotANumber(s) => write!(f, "{s:?} is not a number"),
ParseError::Negative(n) => write!(f, "{n} is negative"),
}
}
}
fn parse_count(s: &str) -> Result<u32, ParseError> {
let s = s.trim();
if s.is_empty() {
return Err(ParseError::Empty);
}
let n: i64 = s.parse().map_err(|_| ParseError::NotANumber(s.to_string()))?;
if n < 0 {
return Err(ParseError::Negative(n));
}
Ok(n as u32)
}
// `finally` is Drop: it runs on every way out of the scope, including early returns.
struct Finally(&'static str);
impl Drop for Finally {
fn drop(&mut self) {
println!(" finally: {}", self.0);
}
}
fn run(input: &str) {
let _cleanup = Finally("release the file");
match parse_count(input) {
Ok(n) => println!(" else branch: got {n}"), // Python `else:`
Err(ParseError::Empty) => println!(" except: nothing to do"),
Err(e) => println!(" except: {e}"),
}
}
fn main() {
for input in ["42", "", "abc", "-3"] {
println!("input {input:?}");
run(input);
}
}input "42"
else branch: got 42
finally: release the file
input ""
except: nothing to do
finally: release the file
input "abc"
except: "abc" is not a number
finally: release the file
input "-3"
except: -3 is negative
finally: release the fileThe sequence of events is the same. Two differences to expect. The error message for "abc" is yours (Python's comes from int), so port the text if anything compares it. And n as u32 in this example would wrap a number above u32::MAX; a real port should check the range (see the thread on integers).
How to do it#
- List the exceptions each function can raise: read the code, the docstrings and the callers'
exceptclauses. Each becomes a variant of the function's error enum. - Change the return type to
Result<T, YourError>. Replaceraisewithreturn Err(...)and calls that may fail withcall()?. - Where Python catches and handles, use
match. Where it lets the exception go up, use?. - Replace
finallyandwithblocks with values that implementDrop(files and locks already do). - Keep
panic!for bugs, where Python usedassertor a deliberate crash (see the thread on panics and errors).
Common mistakes#
- Converting every
except Exception:intoif let Err(_) = ...and ignoring the cause. Log it or return it. - Using
unwrap()where Python would have let the exception propagate. Use?. - Expecting
exceptto catch a panic. A panic is for bugs and is not a normal error path.
Related questions#
What replaces except (A, B) as e?#
A match arm with an or-pattern: Err(MyError::A(..) | MyError::B(..)) => ....
What replaces raise ... from e?#
Keep the cause in the error value, and return it from the source() method of the Error trait (see the thread on Java exceptions).
Sources#
- The Rust Book, "Error Handling": https://doc.rust-lang.org/book/ch09-00-error-handling.html
- Python tutorial, "Errors and Exceptions": https://docs.python.org/3/tutorial/errors.html