CodexBloom - Programming Q&A Platform

Unexpected panic when using `tokio::select!` with multiple futures in Rust

👀 Views: 1 💬 Answers: 1 📅 Created: 2025-06-07
rust tokio async-await Rust

I'm working on a project and hit a roadblock. I'm working with a panic when using `tokio::select!` to await multiple asynchronous operations at once. My code looks something like this: ```rust use tokio::time::{sleep, Duration}; async fn task_one() { sleep(Duration::from_secs(2)).await; println!("Task One completed"); } async fn task_two() { panic!("Task Two failed"); } #[tokio::main] async fn main() { tokio::select! { _ = task_one() => {}, _ = task_two() => {}, } } ``` When running this code, I see a panic from `task_two`, but I expected that `tokio::select!` would handle this gracefully and allow `task_one` to complete. Instead, the entire program crashes with the following message: ``` thread 'main' panicked at 'Task Two failed', src/main.rs:8:5 note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace ``` I’ve tried using `tokio::try_select!` and wrapping `task_two()` in a `std::panic::catch_unwind`, but I still see the panic propagate and terminate my program. What is the correct way to handle potential panics within a `tokio::select!` block? Is there a recommended pattern for ensuring that one task's panic doesn't affect the execution of others? For context: I'm using Rust on macOS. Am I missing something obvious?