Sub topic 9
Handling panics and send errors
This chapter assumes you know how to spawn and join threads, how mpsc channels work, and how a channel closes when its senders or receiver are dropped. It also assumes you are comfortable with Result and unwrap. Here you will see how failures in threads and channels show up as Result values, and how to handle them without crashing the whole program.
A panic stays inside its thread
A panic in a spawned thread does not take down the process. The thread unwinds and stops, and the panic is recorded in the thread's JoinHandle. Calling join returns Err if the thread panicked.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
panic!("boom");
});
match handle.join() {
Ok(_) => println!("thread finished normally"),
Err(_) => println!("thread panicked"),
}
}The panic message is still printed to standard error by the default panic hook. The Err value carries the panic payload, which is a Box<dyn Any + Send>. You can inspect it with downcast_ref::<&str>() or downcast_ref::<String>(), but most programs only need to know that a failure happened.
If you call join().unwrap() on a panicked thread, unwrap panics too, and the failure moves into the joining thread. This is often what you want in small programs. In a larger program, match on the result and decide whether to retry, log, or shut down.
Send errors
A channel has two ends, and each end can notice that the other is gone. The sending side learns this through send, which returns Result<(), SendError<T>>.
send fails only when the Receiver has been dropped. The error gives your value back, wrapped in SendError, so nothing is lost.
use std::sync::mpsc;
fn main() {
let (tx, rx) = mpsc::channel::<String>();
drop(rx);
match tx.send(String::from("hello")) {
Ok(()) => println!("sent"),
Err(e) => println!("receiver gone, got back: {}", e.0),
}
}This prints receiver gone, got back: hello. The field e.0 holds the unsent message.
Receive errors
The receiving side sees closure through recv, which returns Err(RecvError) once the queue is empty and every Sender has been dropped. The for value in rx loop uses this to stop, as covered in the previous chapters. recv_timeout and try_recv use richer error types that separate "nothing yet" from "nothing ever again".
| Method | Empty, senders alive | Empty, all senders dropped |
|---|---|---|
| `recv` | blocks | `Err(RecvError)` |
| `try_recv` | `Err(TryRecvError::Empty)` | `Err(TryRecvError::Disconnected)` |
| `recv_timeout` | `Err(RecvTimeoutError::Timeout)` after the wait | `Err(RecvTimeoutError::Disconnected)` |
Buffered messages are always delivered first. A closed channel only reports Disconnected after it has been drained.
Why unwrap on send is often fine, and when it is not
Many examples write tx.send(x).unwrap(). This is reasonable when a dead receiver means the program is already broken. It becomes a problem when the receiver can legitimately exit early. A producer that panics because the consumer finished first turns a normal shutdown into a failure.
A better pattern is to treat a send error as a signal to stop:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u32>();
let producer = thread::spawn(move || {
for i in 0.. {
if tx.send(i).is_err() {
println!("consumer left, stopping at {i}");
break;
}
}
});
for value in rx.iter().take(3) {
println!("got {value}");
}
drop(rx);
producer.join().unwrap();
}Here the consumer takes three values and drops the receiver. The producer's next send fails, and the loop ends cleanly. The take(3) iterator borrows rx, so drop(rx) runs after the loop finishes.
How the two errors connect
A panic also drops everything the thread owned, including its Sender. A consumer looping on rx therefore ends normally even when a producer panics. Only join reveals that the producer failed, so join your threads and check the result.
Exercises
Exercise
A worker thread calls tx.send(job_result).unwrap(). The main thread drops the Receiver early to shut down. What happens in the worker, and how would you change the code so the worker exits quietly?
Show answer
The send returns Err(SendError) because the receiver is gone, and unwrap panics the worker. The panic is only visible through join. Replace the unwrap with a check such as if tx.send(job_result).is_err() { break; } so the worker stops without panicking.
Exercise
A producer thread panics after sending two messages. The consumer uses for msg in rx. Does the loop end, and how do you learn that the producer failed?
Show answer
The loop ends after the two buffered messages, because the panic drops the producer's Sender and the channel closes. You learn about the failure only by calling join on the producer's handle, which returns Err.