Handle errors in main by returning a Result type and propagating errors with the ? operator instead of calling .unwrap() on fallible operations. This allows the program to exit gracefully with an error message when something goes wrong.
use std::thread;
use std::time::Duration;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let handle = thread::spawn(|| {
for i in 1..10 {
println!("hi number {i} from the spawned thread!");
thread::sleep(Duration::from_millis(1));
}
});
for i in 1..5 {
println!("hi number {i} from the main thread!");
thread::sleep(Duration::from_millis(1));
}
handle.join()?;
Ok(())
}