FAQ - Help and questions

How do Python try, except, else and finally map to Rust?

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

Short answer

A function that raises in Python returns a Result in Rust. except becomes a match on the error, else becomes the Ok arm, and finally becomes Drop, which runs on every way out of the scope. Because errors are values, the possible failures are visible in the signature instead of hidden in the code below.

Checked with rustc 1.93.0, Python 3.13.7, Windows 11

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

#1

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

PythonRust
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 hierarchyan enum with a variant per kind
assert, a bugassert!, 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):

python
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")
text
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 file

Rust (rustc 1.93.0):

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

The 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#

  1. List the exceptions each function can raise: read the code, the docstrings and the callers' except clauses. Each becomes a variant of the function's error enum.
  2. Change the return type to Result<T, YourError>. Replace raise with return Err(...) and calls that may fail with call()?.
  3. Where Python catches and handles, use match. Where it lets the exception go up, use ?.
  4. Replace finally and with blocks with values that implement Drop (files and locks already do).
  5. Keep panic! for bugs, where Python used assert or a deliberate crash (see the thread on panics and errors).

Common mistakes#

  • Converting every except Exception: into if let Err(_) = ... and ignoring the cause. Log it or return it.
  • Using unwrap() where Python would have let the exception propagate. Use ?.
  • Expecting except to catch a panic. A panic is for bugs and is not a normal error path.

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#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet