Sub topic 9
Handling panics and send errors
Threads fail in two ways: a thread panics, or a channel operation reports that the other side is gone. Both show up as Result values, and this chapter covers how to read them and respond.
This chapter assumes you know how to spawn and join threads and how an mpsc channel closes. It also assumes you are comfortable with Result, Option, and unwrap.
What a panic does inside a thread
A panic in a spawned thread unwinds only that thread's stack. Destructors run, and the thread ends. The rest of the program keeps running. The panic message goes to standard error, and join returns an Err when you collect the thread.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
panic!("boom");
});
match handle.join() {
Ok(_) => println!("thread finished normally"),
Err(_) => println!("thread panicked"),
}
}The type of join is Result<T, Box<dyn Any + Send + 'static>>. T is the closure's return value. The error is the panic payload, the value passed to panic!.
The diagram shows the three outcomes of a join.
Reading the panic payload
The payload is a Box<dyn Any + Send>, so you recover its message by downcasting. A panic! with a plain string literal produces a &'static str. A panic! with format arguments produces a String. Check for both.
use std::thread;
fn main() {
let handle = thread::spawn(|| {
let id = 7;
panic!("worker {id} failed");
});
match handle.join() {
Ok(_) => println!("finished"),
Err(payload) => {
if let Some(msg) = payload.downcast_ref::<&str>() {
println!("panicked with: {msg}");
} else if let Some(msg) = payload.downcast_ref::<String>() {
println!("panicked with: {msg}");
} else {
println!("panicked with a non-string payload");
}
}
}
}Code that panics with a custom type, through std::panic::panic_any, falls into the last branch unless you downcast to that type.
If you only want to pass the failure upward, call std::panic::resume_unwind(payload). It re-raises the panic in the joining thread without printing the message a second time.
Returning errors instead of panicking
A panic is the wrong tool for expected failures such as bad input or a missing file. Have the thread return a Result. Then join gives you a nested result, and you handle each layer separately.
use std::num::ParseIntError;
use std::thread::{self, JoinHandle};
fn parse_in_thread(text: &'static str) -> JoinHandle<Result<i32, ParseIntError>> {
thread::spawn(move || text.parse::<i32>())
}
fn main() {
for input in ["42", "abc"] {
match parse_in_thread(input).join() {
Ok(Ok(n)) => println!("parsed {n}"),
Ok(Err(e)) => println!("bad input: {e}"),
Err(_) => println!("thread panicked"),
}
}
}The outer Err means a bug or a broken invariant. The inner Err means a failure the program planned for. Keeping them apart lets you retry or report the second kind and treat the first as a defect.
Spawn can fail too
thread::spawn panics if the operating system cannot create a thread. When that matters, for example in a server near its thread limit, use thread::Builder. Its spawn returns io::Result<JoinHandle<T>>. Builder also lets you name the thread, which makes panic messages easier to read.
use std::thread;
fn main() -> std::io::Result<()> {
let handle = thread::Builder::new()
.name("summer".to_string())
.spawn(|| (1..=10).sum::<u32>())?;
println!("sum = {}", handle.join().unwrap());
Ok(())
}Send errors
Sender::send returns Result<(), SendError<T>>. It fails only when the Receiver has been dropped, because nobody can ever read the message. SendError<T> is a tuple struct that holds the value you tried to send, so the message is not 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, message handed back: {}", e.0),
}
}This ownership detail matters for retry or fallback logic. You can log the value, write it to disk, or send it somewhere else.
Calling unwrap on send is common in small examples. It turns a closed channel into a panic in the producer, which can cascade through your program. A producer usually handles the error by stopping:
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel::<u32>();
let producer = thread::spawn(move || {
let mut sent = 0;
for i in 0..1_000_000 {
if tx.send(i).is_err() {
break;
}
sent += 1;
}
sent
});
let first_three: Vec<u32> = rx.iter().take(3).collect();
drop(rx);
let sent = producer.join().unwrap();
println!("received {first_three:?}, producer stopped after {sent} sends");
}Once the consumer has what it needs, it drops the receiver, and the producer's next send fails. The producer sees the failure and exits cleanly instead of working for nobody.
Receive errors
Each receiving method has its own error type, and each says whether the channel is closed.
| Operation | Error type | Meaning |
|---|---|---|
| `send` | `SendError<T>` | The receiver was dropped. The value is inside the error. |
| `try_send` (`sync_channel`) | `TrySendError<T>` | `Full` means the buffer is full. `Disconnected` means the receiver was dropped. |
| `recv` | `RecvError` | All senders were dropped and the buffer is empty. |
| `try_recv` | `TryRecvError` | `Empty` means no message yet. `Disconnected` means closed and empty. |
| `recv_timeout` | `RecvTimeoutError` | `Timeout` means the sender is alive but silent. `Disconnected` means closed and empty. |
Receiving methods report Disconnected only after every buffered message has been delivered. A producer can send five values and exit, and the receiver still gets all five before it sees the error. The for value in rx loop relies on this. It treats RecvError as the normal end of the stream.
A panic closes the channel
Unwinding drops everything the thread owns, and that includes a Sender. So a panicking producer closes its end of the channel in the same way a normal return does. The receiver cannot tell the difference from the channel alone.
use std::sync::mpsc;
use std::thread;
fn main() {
let (tx, rx) = mpsc::channel();
let producer = thread::spawn(move || {
for i in 0..5 {
if i == 3 {
panic!("failed on item {i}");
}
tx.send(i).unwrap();
}
});
let received: Vec<i32> = rx.iter().collect();
println!("received {received:?}");
match producer.join() {
Ok(()) => println!("producer finished, data is complete"),
Err(_) => println!("producer panicked, data is incomplete"),
}
}The receiving loop ends normally with [0, 1, 2]. Only join shows that the data stops short. This gives a rule: a closed channel does not prove success. Join the producer after the loop and check its result before you trust the data.
If the receiver is the thread that panics, the producer's next send returns SendError. That is why a producer that calls unwrap on send panics too, and the failure spreads backward through the pipeline.
Mutex poisoning
Panics also affect shared state. If a thread panics while holding a MutexGuard, the mutex becomes poisoned. The protected data may be half-updated, and Rust marks it so that later threads notice. Every later lock() returns Err(PoisonError<MutexGuard<T>>).
use std::sync::{Arc, Mutex};
use std::thread;
fn main() {
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let worker_data = Arc::clone(&data);
let _ = thread::spawn(move || {
let mut guard = worker_data.lock().unwrap();
guard.push(4);
panic!("oops while holding the lock");
})
.join();
match data.lock() {
Ok(guard) => println!("not poisoned: {guard:?}"),
Err(poisoned) => {
let guard = poisoned.into_inner();
println!("poisoned, recovered data = {guard:?}");
}
}
}PoisonError::into_inner gives you the guard anyway, so you can inspect the data and repair it. Calling lock().unwrap() everywhere is a legitimate policy: if one thread died in the middle of an update, stopping the others is often the safest response. Recovering with into_inner is right only when you can check or reset the data.
Scoped threads and panics
With thread::scope, you can call join on each handle yourself and handle the Err. If you don't, the scope joins every remaining thread when the closure ends. If any of those threads panicked, scope itself panics after all threads have finished. Joining explicitly is how you contain a panic. Letting the scope join for you is how you pass it up.
Practical guidance
- Use
Resultfor failures you expect. Reserve panics for broken invariants. - Treat a join
Erras a bug report. Log the payload, and decide whether to restart the work or shut down. - Handle
senderrors by stopping the sender. Useunwraponly if a closed channel really is a bug. - Always join producers whose output you rely on, even when the receiving loop ended cleanly.
- Treat a poisoned mutex as a signal to verify the data before you use it.
Exercise
A producer thread sends the numbers 0 to 9 and panics after sending 6. The main thread runs let v: Vec<i32> = rx.iter().collect(); and then prints v. Does the program print an error from the loop? How does the main thread find out the data is incomplete?
Show answer
The loop produces no error. The panic drops the producer's Sender during unwinding, so the channel closes, and iter() ends normally with the values 0 to 6. The main thread learns the data is incomplete only by calling join on the producer's handle, which returns Err carrying the panic payload.
Exercise
What does tx.send(value) return when the receiver has been dropped, and why is the value not lost?
Show answer
It returns Err(SendError(value)). SendError<T> is a tuple struct that wraps the unsent value, so the caller gets ownership back through e.0 and can log it, retry elsewhere, or drop it deliberately.
Exercise
A thread is spawned with a closure that returns Result<u32, String>. Write the match arm patterns for handle.join() that separate a panic, a planned failure, and success.
Show answer
Err(_) is a panic. Ok(Err(msg)) is a planned failure with the error message msg. Ok(Ok(n)) is success with the value n.