From 140f6446b1df390d998d747fe39eaa9aa16bcd8c Mon Sep 17 00:00:00 2001 From: Abeeujah Date: Wed, 13 Aug 2025 14:35:00 +0100 Subject: [PATCH] dev: Use std::panic::catch_unwind for Controlled Panic Handling (Issue 74) --- src/SUMMARY.md | 1 + src/challenges/challenge-65.md | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+) create mode 100644 src/challenges/challenge-65.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 918d42d..624c8a5 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -66,4 +66,5 @@ - [Challenge 62](./challenges/challenge-62.md) - [Challenge 63](./challenges/challenge-63.md) - [Challenge 64](./challenges/challenge-64.md) + - [Challenge 65](./challenges/challenge-65.md) - [Resources](./resources.md) diff --git a/src/challenges/challenge-65.md b/src/challenges/challenge-65.md new file mode 100644 index 0000000..5687340 --- /dev/null +++ b/src/challenges/challenge-65.md @@ -0,0 +1,33 @@ +# Challenge 65 + +### Rust Tip: Use std::panic::catch_unwind for Controlled Panic Handling + +`std::panic::catch_unwind` is a lesser-known tool to catch and handle panics, preventing program crashes in sensitive contexts like FFI or testing. + +It captures panics and returns a Result, allowing graceful recovery. + +```rust +// Rust Bytes Issue 74: Use std::panic::catch_unwind for Controlled Panic Handling + +use std::panic::catch_unwind; + +fn risky_op -> i32 { + panic!("Oh no!"); +} + +fn main() { + let result = catch_unwind(|| risky_op()); + match result { + Ok(val) => println!("Result: {}", val), + Err(_) => println!("Caught panic!"), + } +} +``` + + +You can play around with the code on [Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=ba2d516bc165ee52cc8c7bbe338f7321). + +**Notes:** This function **might not catch all Rust panics.** A Rust panic is not always implemented via unwinding, but can be implemented by aborting the process as well. This function *only* catches unwinding panics, not those that abort the process. + + +Check the docs on [std::panic::catch_unwind](https://doc.rust-lang.org/std/panic/fn.catch_unwind.html) for more information.