乐闻世界logo
搜索文章和话题

How do you handle exceptions and errors in Rust?

1个答案

1

In Rust, error handling is achieved through two primary approaches: recoverable errors and unrecoverable errors. Rust handles these errors using the Result type and the panic! macro.

Recoverable Errors

For recoverable errors, Rust uses the Result<T, E> enum. Result has two variants: Ok(T) representing success and containing the return value; Err(E) representing an error and containing the error information.

For example, when attempting to open a file, it may fail due to reasons such as the file not existing:

rust
use std::fs::File; fn open_file(filename: &str) -> Result<File, std::io::Error> { let f = File::open(filename); f }

Here, the File::open function returns a Result. On success, it returns Ok with a File instance; on failure, it returns Err with an error message.

To handle this error, you can use the match statement to handle each case separately:

rust
match open_file("hello.txt") { Ok(file) => { println!("File opened successfully: {:?}", file); } Err(e) => { println!("File open failed: {:?}", e); } }

Besides match, Rust offers unwrap() and expect() methods for handling Result. Both methods panic on error, but expect() allows you to include an error message.

Unrecoverable Errors

For unrecoverable errors, Rust provides the panic! macro. When Rust code encounters an unrecoverable error, calling panic! stops execution immediately, unwinds the stack, and cleans up data. This is commonly used for testing and handling logical errors.

For example:

rust
fn divide_by_zero() { panic!("Division by zero error!"); } divide_by_zero(); // This will cause a panic

In practice, you might use panic! for errors that should not logically occur, such as array index out of bounds.

Overall, Rust offers a comprehensive error handling mechanism via Result and panic!. Using these tools effectively allows you to write safe and robust code.

2024年11月21日 09:44 回复

你的答案