Skip to content

Instantly share code, notes, and snippets.

@AlexanderHott
Created May 2, 2025 00:07
Show Gist options
  • Save AlexanderHott/7a44be05139f6ef3cbe8f8110a8a9bd1 to your computer and use it in GitHub Desktop.
Save AlexanderHott/7a44be05139f6ef3cbe8f8110a8a9bd1 to your computer and use it in GitHub Desktop.
Rust try/catch
#![allow(clippy::needless_return)]
macro_rules! throw {
($expr:expr) => {
panic!($expr)
};
}
macro_rules! try_catch {
(try $try_block:block catch ($err:ident) $catch_block:block) => {
match std::panic::catch_unwind(|| $try_block) {
Err(e) => {
if let Some($err) = e.downcast_ref::<&str>() {
$catch_block
} else {
unreachable!();
}
}
Ok(v) => v,
}
};
}
fn divide(x: u32, y: u32) -> u32 {
if y == 0 {
throw!("y cannot be zero");
}
return x / y;
}
fn main() {
try_catch! {
try {
let huh = divide(10, 0);
println!("{}", huh);
} catch (e) {
println!("Error : {:?}", e);
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment