How to write a python try/except in rust?

Hi

how do I write the following try/except in python in rust.

try:
    os.remove(file_path)
except Exception as excep:
    logger.error('Failed deleting file %s. Exception thrown: ', file_path)
    logger.exception(excep)

Thanks

Rust uses a different method of error handling than exception catching. It uses Results and Options to describe the correctness and existence of a value respectively.

match std::fs::remove_file(file_path) {
    Ok(()) => {},
    Err(e) => {
        eprintln!("Failed deleting file {}. Error caught: ", file_path);
        return Err(e);
}

Or, since the resulting error already has the filename in it, the .unwrap function will automatically print out the error, saving you the trouble:

std::fs::remove_file(file_path).unwrap();

Or, if you want to actually handle the error:

fn my_function() -> Result<(), std::io::Error> {
    std::fs::remove_file("./file.txt")?; // Will return early if this is an `Err`
    Ok(())
}
2 Likes

What do I need to add in the ok part?

matches must be exhaustive. I could have either used this:

match foo {
    _ => {},
    Err(e) => /* */
}

Or

if let Err(e) = foo {
    /* */
}

To achieve the same result.

It is discarded, so in case your operation is okay (It returns Ok), you can just continue execution afterwards. If you choose to continue execution in the case of an Err, and want the function to do some stuff no matter what the outcome is, then use this:

match foo {
    Ok(()) => {
        //If ok
    }
    Err(e) => {
        //If errored
    }
}
//If the match block doesn't return early, this will be run.

Or, this:

if let Err(e) = foo {
    //If errored
} else {
    //If ok
}
//If the if let..else block didn't return early, this will be run.

You can ignore the Ok value, since it returns the unit (()), which is synonymous with void in other languages, or simply not being anything.

1 Like

You may also find the Error Handling chapters form The Book useful. It explains the various strategies you can use to handle errors in Rust.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.